Redirect non-www to www domain with htaccess

DNS

Suppose you have a website example.com, it can be accessed in two ways.

images/webmaster/redirect-non-www-www-domain-with-htaccess.jpg
  1. http://example.com
  2. http://www.example.com

Though both are same, but in the eyes of Google (and other search engines) these are two different websites. It is a good practice for SEO to use only one version of website. Which one to use? It depends on you. There are both pros and cons of both the versions. I personally recommend the second option with www.

You can redirect your non-www visitors to www website using permanent 301 redirect directive with .htaccess file. This file is located in root directory of your website.

#Force www:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Don't forget to replace example.com with your website domain name.

Explanation

There are three lines. The first line tells apache to start the rewrite module.

The second line specifies that redirect rule only applies when the http host (domain of the url) is not (!) www.example.com. The $ means that the result is for all pages from www.example.com. The [NC] specifies that the http host is case insensitive.

The third and last line specifies the action that should be executed. The dot means any one character. So .* means that a lot of characters, not only one. ^(.*)$ contains the requested url, without the domain. $1 contains the content of the (.*). L means this is the last rule in this run. After this rewrite the web server will return a result. R=301 means that the web server returns a 301 permanent redirect to the browser or search engine.