HTACCESS Tutorial : Apache’s mod_rewrite RewriteCond Statement

Force redirect the NON www version to www. version by HTACCESS

You want to force the www in your domain name (and you don’t have subdomains), as for example our website is http://rankingoogle.com and we want our visitors when type http://rankingoogle.com in their browsers address bar they will be redirected to http://www.rankingoogle.com ( www. added to URL).

You will need Apache’s {HTTP_HOST} variable to see if the www. is already there and, if not, redirect.

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.rankingoogle\.com$ [NC]
RewriteRule .? http://www.rankingoogle.com%{REQUEST_URI} [R=301,L]

Explanation :
{HTTP_HOST} is the Apache variable, which always starts with %.

The RewriteCond %{HTTP_HOST} !^www\.rankingoogle\.com$ [NC] means when the HTTP_HOST or domain name typed is not www.rankingoogle.com then a redirection happens by the following statement.
RewriteRule .? http://www.rankingoogle.com%{REQUEST_URI} [R=301,L]

%{HTTP_HOST} !^www\.rankingoogle\.com$ [NC] means
%{HTTP_HOST} NOT (!) STARTS WITH (^) www.rankingoogle.com ENDS WITH ($)
that is %{HTTP_HOST} not equal to www.rankingoogle.com or that means %{HTTP_HOST} doesnot match with www\.rankingoogle\.com

Here \ is an ESCAPE CHARACTER, . is used by HTACCESS and have a regular expression meaning, so when you need to use . in a regular expr statement you need to write \ before it as \., e.g thanks. should be written as thanks\.

NC means NO CASE, that is uppercase or lowercase letters doesnot matter. This is because domain name is not case sensitive.

Now the RewriteRule statement in HTACCESS
RewriteRule .? http://www.rankingoogle.com%{REQUEST_URI} [R=301,L]

The RewriteRule says to match zero or one of anything then redirect to http://www.example.com with the original {REQUEST_URI}. The R=301 tells the browser (and search engines) that this is a permanent redirection and the Last flag tells mod_rewrite that you’ve completed your redirection.

RewriteCond statements can also create atoms via their regex but these are denoted by %1 … %9 the same way that RewriteRule atoms are $1 … $9. You’ll see these in operation in the Examples.