Automatically Bounce non-www Domain to www. Domain (Canonical Domain Names)

You may have noticed, you may not, but when you go to www.andrewgatenby.com your browser is automatically bounce to andrewgatenby.com - no “www.” in the domain name. This is something I’ve actively done is to include what is called a canonical domain redirect. Basically, if you have a www.domainname.com then you can probably also visit your site by just going to domainname.com and it will still show the same content right?

Well, this to a search engine appears as 2 different domain names with the exact same content - something which could get you marked down in rankings. Using the modern-day witchcraft that is .htaccess we can solve this problem, and automatically bounce domainname.com to www.domainname.com by issuing a HTTP 301 (permanently moved) header redirect:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{http_host} ^your-domain-name.com [nc]
RewriteRule ^(.*)$ http://www.your-domain-name.com/$1 [R=301,nc,L]

If you want to do like what I have done, in bouncing www.domainname.com to domainname.com, then the following will suffice:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{http_host} www.your-domain-name.com [nc]
RewriteRule ^(.*)$ http://your-domain-name.com/$1 [R=301,nc,L]

It’s always useful to put this sort of thing as the first directive in your .htaccess so your server processes this before attempting to process any other redirect/rewrite rules you may have.

If you don’t have access to edit your .htaccess file, or just don’t feel confident in doing so, including the following PHP code as the first thing on any page in your site will do the same redirect:

if($_SERVER['HTTP_HOST'] ==  'your-domain-name.com'){
header("Location: http://www.your-domain-name.com".$_SERVER['REQUEST_URI'], TRUE, 301);
}

Bookmark or share this article:

  • Digg
  • del.icio.us
  • Facebook
  • Google
  • description
  • Reddit
  • StumbleUpon

Leave a Reply

Andrew Gatenby Web Developer, Designer & Geek