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 and we want our visitors when type in their browsers address bar they will be redirected to ( 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 .?{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 then a redirection happens by the following statement.
RewriteRule .?{REQUEST_URI} [R=301,L]

%{HTTP_HOST} !^www\.rankingoogle\.com$ [NC] means
that is %{HTTP_HOST} not equal to 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 .?{REQUEST_URI} [R=301,L]

The RewriteRule says to match zero or one of anything then redirect to 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.