How to enforce redirect from non-www to www via .htaccess file

On one of my sites I had this tiny little problem – I needed to enforce redirection from myexamplewebsite.net
to www.myexamplewebsite.net because both websites were active and thus provided duplicate content which is very bad for Google ranking.

Ok so how to do it?

1. In your web root (usually where index.html or index.php is) find file .htaccess (yeah it really starts with dot in the beginning which marks “hidden” in Unix structure)

2. edit it and add following:

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

3. save it and upload it

4. Profit! 🙂 – Now when you enter into address bar: myexamplewebsite.net it should redirect you to www.myexamplewebsite.net right away – no duplicate content anymore!