1
votes

I have a site example.com. Any traffic to www.example.com is redirected to example.com in the .htaccess file using:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

This piece of code that I swiped of the interweb works fine.

I have now added a subdomain subdom.example.com. Similar, any traffic to www.subdom.example.com should be redirected to the non www canonical version.

The following code does not work:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)$ http://subdom.example.com/$1 [R=301,L]

Presumably redirects work a little differently where subdomains are involved. Could anyone share how I would edit the above snippet to redirect any www. traffic to the canonical non www. subdomain version?

1

1 Answers

2
votes

I believe you don't have sufficient RewriteCond conditions for both redirects. What is happening is that first one is unconditional redirect and since it appears first it always fires and 2nd one never fires.

Replace your code with this:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On

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

Above code will work with both of your domains.