Question

I'm facing an issue with .htacess when combining 2 mod_rewrite at the same time:

  • remove trailing slash
  • redirect non-www to www

Here is my .htaccess file

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^(.+)/$ http://www.domain.com/$1 [R=301,L]

# Remove trailing slash
RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

They worked perfectly when I just used one of them, but when i put them together, the page just keep loading like forever.

Please help me to find a way that can use both of them in the same .htaccess

Was it helpful?

Solution

Try this:

RewriteEngine on
Options +FollowSymLinks
RewriteBase /
#Non www to www without trailing slash
RewriteCond %{HTTP_HOST} ^(domain\.com)/?$ [NC]
RewriteRule ^(.*/?[^/]+)/?$ http://www.domain.com/$1 [R=301,L,OR]
RewriteRule  .* http://www.domain.com [R=301,L]

Results:

http://domain.com/aa/ to http://ww.domain.com/aa

http://domain.com/aa/bb/ to http://ww.domain.com/aa/bb, etc.

All except http://domain.com/ that always will be http://www.domain.com/with trailing slash

OTHER TIPS

NON-WWW URLS TO WWW USING HTACCESS:

You can add the following code to your .htaccess file, you can find it in your website root directory, if you don't find it you can copy this in a text editor and save it as .htaccess, then upload it.

p.s.: Make sure that you backup the .HTACCESS file before you proceed. Incorrect codes can lead to 500 errors.



    RewriteEngine On
            RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
            RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]


Remove trailing slash

Be careful when turning off the trailing slash. If your host has mod_dir enabled, make sure that you turn off the directory slash, which is enabled by default. This directive will add a trailing slash at the end of a directory regardless of the rules you set up. To disable this, add this to the top of your htaccess file:


DirectorySlash Off

Your browser and even your server, by default, add a trailing slash to a directory. It is done for a reason. If you must strip the trailing slash though, this is how you would do it:



    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !(.*)$
    RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top