Apache Server version 2 supports use of URL rewriting i.e. mod_rewrite. With the help of this, one can keep URLs of website clean and neat. With the help of mod_rewrite and .htaccess, one can redirect visitors who are visiting non-www to www URL of website.
Some website owners prefer to use www.sample-site.com where as some prefer sample-site.com. But from Search Engines point of view, both websites are different, hence a Search Engine can penalize a website for duplicate content.
Hence is it very important to keep only 1 style of your website URL. Following are the .htaccess code which will help you in this matter.
Before moving ahead, we would like to tell you that this works only with Linux Based Apache Server. Go to your root directory of website and create a file named as .htaccess
To Redirect from non-www to www
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
To redirect from www to non-www
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]
Now don’t forget to replace your domain name with yourdomain.com. Both of the above URLs send 301 redirection.
