Redirect non-www to www domain with htaccess

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

Redirect non-www to www domain with htaccess

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} !^$ [NC]

RewriteRule ^(.*)$$1 [L,R=301]

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


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 (!) The $ means that the result is for all pages from 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.