Automatically redirecting to the www no-www prefix

There's a common SEO claim that a double domain pointing to the same content isn't good for SEO due to what can be perceived as duplicate content . Use the rewrite module to redirect all domain.com to www.domain.com by adding the following to your .htaccess :

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,QSA,L]

</IfModule>

Some people have trouble using this version in some cases, like when using the blog in a subdirectory such as in /blog/. Another good version of the .htaccess that you can try, and that I use here with the /tech/ directory is :

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule .? http://www.domain.com%{REQUEST_URI} [R=301,L]

</IfModule>

If you wish to redirect from the www. prefix to not having a www. prefix add the following:

<IfModule mod_rewrite.c>

RewriteEngine On

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

</IfModule>

Notes :

  • You'll need, ofcourse, to change the domain.com to your domain.
  • Take extreme care where you place this code in your .htaccess. It is advisable to put this before other redirections, so those will not be lost.
  • Drupal's default .htaccess looks like this but is extremely faulty (no $1 at the end) and will redirect to your frontpage, which is something you really don't want. If you're running Drupal, check that you have this format and are not using Drupal's suggestion (4.7, 5.0, 5.1 versions).
  • If you're using WordPress, there are a few plugins that are suppose to do this automatically for you, like - Enforce www. Preference ; WordPress no-www ; WWW-Redirect. I believe you should do these manually with your .htaccess, but if must - then use those with care, and test your results thoroughly.
  • It is possible to set the preference for Google's search engine through the Sitemaps. Open your sitemaps->Manage->Preferred domain and set what you want Google to use.
  • I've met a few who thought that if you have a subdomain like subdomain.domain.com then this issue doesn't exist. It does, and you can have both www.subdomain.domain.com and subdomain.domain.com pointing to the same place. It's interesting that while some choose the www prefix for their main domain, they prefer to not use it for the subdomain, and the .htaccess should be set accordingly.

If you wish to redirect a page through using PHP, then apply the following index.php to where you wish to redirect (change http://www.newdomain.com/ to the domain you're redirecting to):

<?php
header( "HTTP/1.1 301 Moved Permanently" );
header( "Status: 301 Moved Permanently" );
header( "Location: http://www.newdomain.com/" );
exit(0); // This is Optional but suggested, to avoid any accidental output
?>