Torkil Johnsen

My personal piece of cyberspace

Some easy use of mod_rewrite

Posted in Content management,Search engines on Jan 16th, 2008

Here are some easy code snippets that comes in handy on all websites I set up. Consistent urls are important for search engines, so I have a few small code snippets to make sure everything works as planned.

Just insert one of the following blocks in your .htaccess file in your site root. Make sure you replace with your own domain name, and also make sure that you leave the backslash in example\.com in the first line of the code.

# force www IN URL
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$$1 [R=301,L]
# END force www IN URL

# force removal of www IN URL
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$$1 [R=301,L]
# END force removal of www IN URL# force www IN URL

And here is a snippet that can forward users from one domain to another automatically. Nice to have if your site has got one or more aliases. Notice that all the domain aliases have [NC,OR] at the end of the line, while the last alias just has [NC].

# forward from domain aliases
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain2\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain3\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?and_so_on\.com [NC]
RewriteRule (.*)$1 [R=301,L]
# END forward from domain aliases

One last thing: RewriteEngine On is just something you need to write once in your htaccess file, so if you use two of the above snippets, make sure you remove that from the second block.


Creative Commons License
This work by Torkil Johnsen is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.