Canonical URLs
January 2, 2012Canonicalization is simply the process of clarifying and announcing (to search engines) which URLs are the best ones to rank. An example of a common canonical URL issue, which was discussed earlier, is duplicate content. Not declaring a canonical URL may split your ranking among multiple URLs, which will ultimately affect your ranking. The www vs non-www issue is definitely something you want to take care of sooner rather than later, because once a search engine has ranked both versions, it may take a while for the “link juice” to redirect – but it will, eventually.
Redirect non-www to www:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Redirect www to non-www:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
The code, when added to a .htaccess file and uploaded to the root directory of your web server, will redirect requests to the respective non-www to www, or www to non-www, based on one of the redirect instructions above.