Non WWW to WWW and WWW to Non WWW Redirect By .htaccess

Hello Friends, Yesterday i got one problem in domain name with www and also without www (non www). Our site URL with WWW and without WWW is very important for seo purposes and also for google. According to Matt Cutts url canonicalization article we have only one url for whole site like with www or without www. If you are using site url’s with www then non www urls should have 301 permanent redirect to www urls. So to do that first you have to check that your dedicated web server support URL rewriting or not? If you want to check that your server supports URL rewriting or not then make one php file and after that paste code shown below :

<?php

phpinfo();

?>

Upload this file to server and check this file in browser. When you open this file in browser you will see so many configuration settings in that file so just try to find out “mod_rewrite” (without quotes) in that file. If you find that string then your server haveing URL rewriting enabled but if you don’t find that string then your server not having URL rewriting enabled. To enabled URL rewriting you have to mail to your hosting or some hosting provide URL rewriting enable/disable option in cPanel->Settings.

Non WWW to WWW Redirect

Now we suppose that URL rewriting is enable on server and we want our all urls redirected from non www to www. Now make one file .htaccess (If not exists on server) and put code shown below :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yourwebsite.com [NC]
RewriteRule ^(.*)$ http://www.yourwebsite.com/$1 [L,R=301]
</IfModule>

After putting this code in .htaccess upload it to root folder of your server. Please don’t forget to put your website/your domain name instead of yourwebsite.com in that code.

WWW to Non WWW Redirect

To redirect from www to non www urls you must put down code shown below :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourwebsite.com [NC]
RewriteRule ^(.*)$ http://yourwebsite.com/$1 [L,R=301]
</IfModule>

Again please don’t forget to put your website/your domain name instead of yourwebsite.com in code.

By this way you can redirect your site urls from www to non www or non www to www. For more information on URL canonicalization read Matt Cutts url canonicalization article.

Subscribe to PHP Freelancer

Enter your email address: