Tuesday, 20 July 2010

Redirect non-www requests to www with .htaccess

This tutorial explains how to use the .htaccess file to redirect all non-www requests to the www version of your domain. Visitors who thus type http://your-domain.com will automatically get redirected to http://www.your-domain.com.

The .htaccess file

You only need a regular text editor to create the .htaccess file, and, if you are using Windows, I recommend using Notepad as it is fast and if you want to edit your .htaccess file later, you can just drag your file onto Notepad to open it. Creating the .htaccess file is easy as it's merely a matter of typing in yor commands but people usually have problems saving the file with the correct name as Windows automatically adds the .txt extension at the end of the file whereas .htaccess's extension is technically htaccess itself with no file name.

To save your .htaccess file correctly, you thus need to save it by entering ".htaccess" in double quotes as shown below. By doing this, you are forcing Windows to use htaccess as the extension and the .htaccess file will be correctly saved.

Naming your .htaccess file in Notepad

Redirect non-www domains to www domains

Allowing your visitors to access both non-www and www versions of your website will lead search engines into believing that you have a lot of duplicate content, so it makes sense to redirect all non-www requests to your www domain.

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

These two lines will thus redirect all yourdomain.com requests to www.yourdomain.com, so that your web pages always available from only one URL.

One important thing to keep in mind is that you need to escape all periods in the RewriteCond line with a period. For example, in a .co.uk domain, your non-www redirection would look like the following:

RewriteCond %{HTTP_HOST} ^yourdomain\.co\.uk
RewriteRule (.*) http://www.yourdomain.co.uk/$1 [R=301,L]

Obviously, it is also possible to redirect all www requests to the non-www version of the domain, as demonstrated below:

RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com$ [NC]
RewriteRule ^(.*) http://yourdomain.com/$1 [R=301,L]