How to Add – Remove the WWW Prefix from Domain Name Using .htaccess

November 16th, 20092 Comments

To avoid duplicate content problem with search engines, you have to redirect all pages to one common URL.

This you can achieve using mod_rewrite of apache and .htaccess.

To redirect any URL starting with www.domain.tld to domain.tld, you have to add the following code to .htaccess file.

Do a 301 redirect for all http requests that are going to the wrong url.

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

or

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

To redirect domain.tld to www.domain.tld -

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

or

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

Related Posts:

Tagged : ,

2 Responses

  1. Please note the Google PageRank goes up to 10 and the best alexa rating is 1. Short Url Redirect

  2. What if this is done at DNS level. How can it be changed?