Friday, November 2, 2012

Redirect non www to www on an apache server

What is .htaccess file?


.htaccess is a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software.

.htaccess code


If your website is hosted on an apache server, this redirect from non www to www is a simple implementation. Add this to your .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule (.*) http://www.domain.com/$1 [L,R=301]

Add the above code to you .htaccess file and replace domain.com with your domain name.

Explain by dense13


The first line sets a condition: only if the condition is true, the second line will be processed. The condition could be 'translated' to: "if the host name doesn't start with www .". The regular expression !^www\. means this:

! = not

^ = start

\. = . (the backslash is the escape character, because dots have a special meaning in regular expressions, and therefore must be escaped)

So !^www\. means "doesn't start with www.".

The second line is the actual rewrite rule: again it uses regular expressions to match certain urls, and then rewrites them to something else. The first part is the regular expression:

^(.*)$

This means: anything! You already know the ^ sign. The (.*) bit means zero or more characters (the dot means any character, the asterisk means zero or more). The final $ means 'end'.

Then comes the bit that says how to rewrite the url:

http://www.%{HTTP_HOST}/$1 [R=301,L]

%{HTTP_HOST} will be replaced by the host name (i.e. xyz.com).

$1 references whatever was matched in the regular expression between the brackets, which in this case is everything.

The [R=301,L] means "inform the user agent that this is a permanent redirect (HTTP 301 code), and don't process any more rewrite rules (if there were any after this one).

----------------------
- a well organized authentic experienced SEO/SEM/SMO/PPC including according to present scenario. who is present in Delhi the capital of India.

1 comments: