How can I force URLs to have [or not have] the WWW subdomain?

A number of search engine will index sites with and without the www. prefix as separate sites ( for example http://www.bradtrupp.com and http://bradtrupp.com ) and this can lower your position in search results. Besides, forcing consistency is a good thing too.

Side Note: This article was written in 2008 so some of the references may be out-of-date.

The solution is easy using Apache’s mod_rewrite in your .htaccess file.

Create a file named “.htaccess” or modify your existing one and add the following commands – remember to change ‘example’ and ‘com’ to your domain name and tld.

RewriteEngine on
Rewritecond %{HTTP_HOST} ^example\.com
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

This rule forces www to be added to the URL when the user did not put it in there. This means that all your content will be seen at http://www.example.com.

The “R=301” tells anyone requesting the “short” URL that it has been permanently moved to the “www” version. And the “L” means this is the last step in the rule.

If you want to go the other way and take out the www instead, then the entry would look like this:

RewriteEngine on
Rewritecond %{HTTP_HOST} ^www\.example\.com
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]