Subscribe

Ensuring canonical urls with .htaccess

I was reading an article about SEO on Red Cardinal and I came across the Canonical URL issue for the first time. Apparently Google may treat http://aidanf.net and http://www.aidanf.net as separate sites. I am inconsistent in the url I use for this site - sometimes I use one and sometimes the other. Even if Google doesn’t treat these urls as distinct it is good to have consistency in using one or the other. Luckily it’s easy to setup a permanent redirect of one to the other. I added the following to my .htaccess file.

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

The first two lines are conditions and the third line is the action to take if the first two conditions are met. The conditions specify that the url doesn’t start with www and that the HTTP_HOST is present (this excludes relative urls) is present. The action is to permanently redirect (301) the url to the same url with www appended to the start. So now a url like http://aidanf.net/rails_user_authentication_tutorial gets redirected to http://www.aidanf.net/rails_user_authentication_tutorial.

Very good point - but probably best not to use www - see: http://no-www.org/index.php

I saw the no-www site a while ago. I thought about doing it the other way round i.e. redirecting urls with www to ones without www. But I decided to use the www since most web users expect www and the url looks more symetrical with www prepended:)

Thanks for the info. Is it really necessary to do it with a RewriteCond? Can't you just use RewriteRules?