CodingGuru CodingGuru - 1 month ago 14
Apache Configuration Question

Redirect without www plus add trailing slash?

I have the following in my .htaccess file

RewriteEngine On
RewriteCond %{REQUEST_URI} ^www.mysite.com [NC]
RewriteCond %{REQUEST_URI} !\.[^./]+$
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ mysite.com/$1/ [R=301,L]


I am trying to get it to redirect all URLs with no www and also add a trailing slash at the end of a URL at all times.

This is working if you hit it directly without the www, but if you try it with the www it fails and does not remove it nor add the trailing slash.

Answer

Here is a single rule to remove www and add trailing slash:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*?)/?$ http://%1/$1/ [R=301,L,NE]

This also avoids hardcoding your domain name in the rule.