htaccess

10
Sep
2011

Redirect WWW to Non-WWW and Vise Versa

It's a rather common task - to make one of the two aliases the main one (with www or without) and set up redirection from the second alias. For instance, we can set up www.site.com as a main domain, so site.com will redirect us to the www.site.com. Or vise versa, we can set a redirect from www.site.com to site.com so the main domain become the one without www.

For this purposes, we should use 301 redirect, which is permanent redirect.

The easiest way to achieve this goal is to use .htaccess, which should be exist in your site's root directory. You should have Apache's mod_rewrite module has been installed too, but frequently it's already installed on your web hosting by default.

If you want to make domain without www the main one, you should add to your .htaccess the code below:

  1. <IfModule mod_rewrite.c>
  2. RewriteEngine on
  3. RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  4. RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
  5. </IfModule>

Or, if you want to make domain with www the main one, you should use this:

  1. <IfModule mod_rewrite.c>
  2. RewriteEngine on
  3. RewriteCond %{HTTP_HOST} !^www\. [NC]
  4. RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  5. </IfModule>
Category: 
0