Saturday, May 29, 2010

Redirect non-www to www and vice versa using .htacccss

In this post with simply two lines of code I will show how to redirect all non-www traffic to www traffic as well as how to redirect all www traffic to non-www by editing .htaccess file.

Redirect non-www to www
Edit .htaccess file and add following lines,
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
This will redirect any non-www to www site regardless of domain name.

Redirect all www to non-www
Edit .htaccess file and add following lines,
RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain-name\.com$ [NC]
RewriteRule ^(.*)$ http://domain-name.com/$1 [R=301,L]

Here we explicitly mentioned domain name.

In the example replace domain-name with your domain. For example for site http://arju-on-it.com my .htaccess of redirect all www to non-www will look like below,
RewriteEngine On
RewriteCond %{HTTP_HOST} !^arju-on-it\.com$ [NC]
RewriteRule ^(.*)$ http://arju-on-it.com/$1 [R=301,L]

No comments:

Post a Comment