Redirect Visitors From Non-WWW To WWW With .htaccess And mod_rewrite

Apache’s mod_rewrite module is a very robust and effective tool and can be used for lots of important stuff related to your website. One of it’s application is to force visitors and search engine robots to either the WWW form of your website (e.g. www.ireadysites.com), or the non-WWW form of your website ( i.e. iReadySites.com).

To accomplish the desired objective you need to add just three lines of code to your .htaccess file. For those of you that don’t know, an .htaccess file is a simple ASCII file that you can create in a text editor like Notepad. The actual name—or rather, the extension—of the file is .htaccess. It’s not file.htaccess, or index.htaccess, or anything else, it’s simply named .htaccess.

Look for it in your site’s root folder/directory (which in most cases would be ‘pubic_html’ or ‘www’ – It does not matter which directory you choose, as they are both the same thing. ). If it’s not there simply use a text editor, insert the code written below, save and upload to your website root. You are now all set to send users typing your website address without www (i.e. yourdomain.com) to the WWW version of your website. Here is the code:

RewriteEngine On

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

Easy, isn’t? Now to send visitors to the non-WWW version of your website. The following lines of code would automatically redirect users typing your domain name with www (i.e. www.yourdomain.com) to the non-WWW version:

RewriteEngine On

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

But this is something you should think about at the earlier stages (design and development) of your web site. Applying this after you’ve already been indexed may result in loss of PageRank or even a complete removal and then re-index of your website by the search engine bots.

Hope this’ll help… cheers

Please click below for an updated post especially with regards to subdomains.

Add a Comment

Your email address will not be published. Required fields are marked *