Adding www to your domain with Apache

A question I see asked in lots of places online is how to ensure that a visitor to your site is visiting and not just There are lots of good reasons for wanting your visitors to visit the one address rather than both, such as making sure all link and bookmarks count towards the one page, rather than being shared between two.

Some of the solutions I've seen have been crazy, like editing every php file on your site to check what the address is, and redirect depending on whether the www is included or not. If you're using Apache then a very simple solution exists with mod_rewrite. All you need to do is create a .htaccess file in the root directory of your website and add the following lines:

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} !www RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] </IfModule>

Mod_rewrite is very powerful, and allows you to do far more than just add www. to your URLs. If you're interested in more information then official documentation is a great place to start, and contains lots of examples.

Posted on 18 Feb 2008
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.