Thursday, January 7, 2010

Apache: Redirect from non-www to www form

Here is a reason when you need to redirect users coming to your site without "www" to the one with "www": You have submitted your sitemap to the search engine with your website name as "http://www.yourwebsite.com". Now you need to tell the search engines which url you prefer to be canonical. So you need to redirect the "http://yourwebsite.com" to "http://www.yourwebsite.com".

So now here is a way to do that with apache.

1) Enable mod_rewrite in your apache config file.

2) Write following lines in you .htaccess file:



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



So, you are done.

If you don't know what the .htaccess file is. Here is a small information about it. It is placed at the root folder of your web application. And it overrides the configuration of the your apache server's main config file. So for shared hosting when you don't have access to main config file, you can do your application specific settings in this .htaccess file.

No comments:

Post a Comment