Suppose you have a site at www.w3central.com and don’t like the non-www verion w3central.com. A simple trick to redirect a non-www version of your page to the www version is adding this to your htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^w3central\.com
RewriteRule ^(.*)$ http://www.w3central.com/$1 [R=301,L]
Some explanation for those interested.
RewriteEngine On
This enables the runtime rewriting engine.
RewriteCond
RewriteCond %{HTTP_HOST} ^w3central\.com
This defines a rewriting rule condition. The rewrite rule that follows it on the next line will only be considered if these conditions apply. The “\� in “w3central\.com� is used to have the dot “.� as “.�, else “.� means “any single character�. The “^� before “w3central\.com� tells apache to look at a string that starts with “w3central\.com�. Or better, since we know now what the “\� means: starts with “w3central.com�.
In short, the rewrite condition tells apache only to use the rewrite rule if the http host matches w3central.com.
RewriteRule
RewriteRule ^(.*)$ http://www.w3central.com/$1 [R=301,L]
The “^â€? is the same as above, only this time the “$â€? plays a role too. “^something$â€? matches anyting that starts with “somethingâ€? and ends with “somethingâ€?. This time we find a dot in between that isn’t escaped by a slash, so it can stand for any character. The asterisk “*â€? behind it means “any number of the precedingâ€?. So in our case: any number of “.â€? or “any number of charactersâ€?. It’s in between “()â€? which just tieds it together.
The second part of the rewrite rule tells apache to what it should be rewritten if “ ^(.*)$â€? is matched. We see our www-version of the url followed by “$1â€?. “$1â€? is just the first variable of the pattern it had to match. This variable is “(.*)â€?. If this variable matched “mybigsecretâ€?, the url will result in http://www.w3central.com/mybigsecret. There can be more than one variable but I’ll leave that for another time.
Finally “[R=301,L]â€? tells apache the redirect (the “Râ€? flag) should be a permanent one (301 means that the page is permanently moved). The “Lâ€? flag tells apache to stop the rewriting process and don’t apply any more rules.
Summing it all up
What happens is that the rewrite engine is turned on. If the http host matches “w3central.comâ€?, the url is rewritten according to the rewriterule and redirects to this new url with a 301 permanently moved for the old one, and stops the rewriting. In practice: if apache encounters a request to w3central.com/somepage (rewrite condition), we’ll get a 301, and are redirected to www.w3central.com/somepage (rewrite rule).