17 October 2007 - 18:54[How to] force "www." on your website
I recently added some lines to my website’s .htaccess that force a “www.” on the front of my domain. If you try to go to my website by typing just dmack.ca, you’ll notice it automatically redirects you to www.dmack.ca.
It’s best practice to either always force the www. or always force no www., but not use both. There are a bunch of reasons to do this, and they vary depending on what kind of website you run:
- Cookies. If visitors can access your site with and without the “www.” (two different URLS as far as the cookies are concerned), it could cause problems.
- Likewise with $_SERVER['REQUEST_URI'] and such things if you’re running scripts.
- The most cited reason I see for this is that it hurts your pagerank. Apparently you could get penalized for duplicate content.
In the interest of avoiding the above problems, and any sort of minor confusion, here’s how to set up a painless automatic redirect in your .htaccess file.
I’ll use my own domain in this example. Just add the following lines:
# redirect dmack.ca to www.dmack.caRewriteCond %{HTTP_HOST} ^dmack.ca [NC]RewriteRule ^(.*)$ http://www.dmack.ca/$1 [L,R=301]
The first line is a rewrite conditional directive that basically ensures the URL starts with “dmack.ca”. The [NC] means it’s not case sensitive. The second line is an ordinary rewrite directive that matches everything and does a 301 redirect to the properly formatted URL (complete with “http://www.”). This matches the url if it begins with dmack.ca, but it could just as easily match any url that isn’t www.dmack.ca (think: exclamation mark negates… !^www.dmack.ca)
