Force users to use the WWW or Non-WWW version of your domain

To avoid duplicate content in search engines you can force users to use either the www or the non-www version of your website domain.


This avoids search engines such as Google indexing two versions of your domain, something which is quite common because people link to both www and on-www versions of a domain (known as the www/non-www canonical issue).

It really doesn’t matter if you use www.yoursite.com or yoursite.com. I personally use www on most sites I own however many people prefer to drop it, it’s really up to you.

Force users to use http://www.yoursite.com

To force users to use the www version of your domain all you have to do is add the following code to your .htaccess file (just replace yoursite.com with your domain name).


# Redirect non-www urls to www
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.yoursite\.com
RewriteRule (.*) http://www.yoursite.com/$1 [R=301,L]

Alternatively you can use :


# Redirect non-www urls to www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

Force users to use http://yoursite.com

To force users to use the non www version of your domain all you have to do is add the following code to your .htaccess file (just replace yoursite.com with your domain name).


# Redirect www urls to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.yoursite\.com [NC]
RewriteRule (.*) http://yoursite.com/$1 [R=301,L]

Alternatively you can use :


# Redirect www urls to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com
RewriteRule (.*) http://example.com/$1 [R=301,L]


Notes about this technique

Many popular scripts, particular content management systems (CMS’s) edit the .htaccess file and add their own redirection so you may not have to add any of the code noted above. Infact, by adding the redirection code noted above you could actually mess things up.

For example, the popular blogging script WordPress adds redirection to the .htaccess file. You simply chose the correct domain name in the admin panel and it takes care of everything else. And if you do add the code to the .htaccess file it messes things up a little. It does still redirect non-www to www (and vice versa) but it just redirects the visitor to the home page (ie. http://yoursite.com/folder1/page1 would redirect to http://yoursite.com/ instead of http://www.yoursite.com/folder1/page1).

If this sounds a little confusing, don’t worry. Just remember that certain scripts already apply a redirection and so trying to add a redirection code to the .htaccess file can mess things up, at the very least it will unlikely work the way you want it to.