Be Google’s friend: Make your URLs canonical with .htaccess
July 18, 2008
Filed under
.htaccess, Apache, Server Management
This subject is… is… well ![]()
Every second site on the net has at least one article about this subject. But to be honest, it’s good to have so many articles about this, in a way. At least people recognize they should use it. Or not.
So, what’s the fuss around the URL canonicalization? One thing only: the search engines and their hate of duplicated content. If your website is accessible both on www.example.com and the plain example.com the search engines will index both areas, they think you duplicated your content to get more positions in the search results, so they penalize your domain. Weird. They should know it’s the same website, or at least the coders should teach them that www is the same with non-www. Or at least on well-configured servers.
So, here pops Apache in and throws a resolution for the issue: the mod_rewrite engine, again. You will have to have mod_rewrite bundled into Apache and working correctly.
As always, here’s the code for those who just want to copy&paste and then the explanation for all the lines.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^/(.*) http://example.com/$1 [R=301,L]
That is. Placed in a .htaccess file, it will redirect with code [301:Moved Permanently] all the queries sent to the www.domain.com to domain.com. Now let’s explain it line-by-line:
- We switch On the mod_rewrite module, thus telling Apache we want to work with it.
- If the hostname contains “www”, apply the rule, so this a condition
- This last line is the rule which has to be done if the condition can be applied on the HTTP request. In our case do a 301 redirection to the non-www version of the site
That was all. Search engines are now happy, World saved again.
As always, if something is unclear, drop a comment and i answer as soon as possible.
Possible related posts (automatic):
Related posts brought to you by Yet Another Related Posts Plugin.



















Comments
Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!
If you want to use your OpenID, fill out the field labeled "Website" with the OpenID URL. The other fields may remain empty.