Miura-shi
Miura-shi

Reputation: 4519

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.

Upvotes: 1

Views: 302

Answers (2)

anubhava
anubhava

Reputation: 785886

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.

Upvotes: 2

Panama Jack
Panama Jack

Reputation: 24478

You can use these two rules to enforce all the time. Plus you have syntax error in your first condition. It should be HTTP_HOST not REQUEST_URI

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

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

Upvotes: 1

Related Questions