The canonical redirect

Let's say you have a website www.example.com and because of the great content you have put up there, people are starting to link to it.
That's fantastic I hear you say, or is it?
Because people are sloppy, so the link to example.com as well as www.example.com, so when search engines come by they will find example.com and www.example.com
But now you have another even bigger problem, because these search engines will think www.example.com and example.com are two different sites with the same content, and then you will have to wait and see which they will serve to your potential clients. Or worse, you get banned.

OOPS.
What to do now?

Meet the canonical redirect

The canonical redirect, or the 301 redirect will help you here.
And it is not that hard to do, most servers will let you make an .htaccess file.
So all you have to do is that when a client requests example.com you redirect the to www.example.com

Easy peasy.

But how to do that?

Well, when you access your site through ssh and go to your webroot there is probably an .htaccess present because of Drupal, Wordpress, Joomla, or whatever CMS you are using.
So you just add this to the top:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule ^(.*) http://www.example.com$ [R=,L]
</IfModule>

This piece of code first check if you have the rewrite module installed. So if you don't have that is will just do nothing. Your redirects are not working, but at least you don't get an error.
Then is switches on the RewriteEngine.
And here are the two lines that do all the work.

  1. If the host does not start with www.example.com
  2. Rewrite it to http://www.example.com/whatever_the_user_typed using a 301 redirect

And that's it. These 5 lines will make you all the difference.

English