Force Redirecting non-www to www with .htaccess

Some times you need to redirect all non-www requests to www for your site, this will be useful to avoid duplicate content, as the search engines may crawl tow copies of the same page, one with www and the other without, to get ride of this problem, you can use 301 redirect to tell search engines that the non-www page is the same as www one.

Making this type of redirect is easy as a piece of cake, just use the following lines in your .htaccess file, where website.com is your domain name.

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

If you want a generic solution regardless of the domain name, you can use the following lines:

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

This will work for any domain.

 

Comments
  1. No comments yet!, be the first to post a comment.

Your email will not be published, The required fields marked with '*'

*