When using multi-site configurations in Drupal 4.7, and you want to use URL rewriting in .htaccess to force 'www.' or non-'www.' subdomain access, the rewrite rules used in the standard .htaccess file may be problematic.
# If you want the site to be accessed WITH the www. only, adapt and uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
# RewriteRule .* http://www.example.com/ [L,R=301]#
# If you want the site to be accessed only WITHOUT the www. , adapt and uncomment the following:
# RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
# RewriteRule .* http://example.com/ [L,R=301]
This is due to the fact that the condition they are testing for is: "When the HTTP_HOST header is NOT www.example.com (or example.com in the latter example), rewrite the url with www.example.com (or example.com)"
Using this method will cause you trouble if you have two or more sites running on the same code base in 4.7, because, the HTTP_HOST header will trigger an erroneous match and will rewrite the URL to one of the other sites.
For example, if you have two domains, tom.com and jerry.com, both running off the same code base and you want to force both to use the non-www URL form, you should use the following .htaccess rewrite entries:
RewriteCond %{HTTP_HOST} ^www\.tom\.com$ [NC]
RewriteRule ^(.*)$ http://tom.com/$1 [L,R=301]RewriteCond %{HTTP_HOST} ^www\.jerry\.com$ [NC]
RewriteRule ^(.*)$ http://jerry.com/$1 [L,R=301]
Another advantage to the above form, is that the URL will be rewritten to include the URL path after the hostname, so someone who tries to go to http://www.tom.com/node/123 will get a 301 redirection to http://tom.com/node/123.
Resources
- Excellent list of resources [brainstormsandraves.com]
- Apache.org mod_rewrite docs
- Thanks and a tip o' the hat to more .htaccess tips and tricks [corz.org] for the enhanced rewrite expressions.
a more flexible solution
I have a generic solution, non need to include every domain name you host
# check that HTTP_HOST isn't empty
RewriteCond %{HTTP_HOST} !^$ [NC]
# that ‘www’ is missing
RewriteCond %{HTTP_HOST} !^www\. [NC]
# save HTTP_HOST in %1
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
# wrap up
RewriteRule ^(.*)$ “http://www.%1/$1″ [L,R=301]
# et voilà !