Saturday, November 20, 2010

Basic Apache Rewrites

URL rewriting is a powerful technique not just for the Webmasters, but also for the SEO and Security guys. This article will give an overview towards the most common ways to implement rewrites using the Apache mod_rewrite.

A basic rewrite will look like this:

RewriteRule ^(.*?)/abc(.*) $1/def1$2 [R=301]



So for example if you try to access  http://www.r00tb0x.com/abc123/whatever you will be redirected to http://www.r00tb0x.com/def123/whatever.

The R=301 flag tells Apache that the rewrite is a Permanent (301) Redirect. Furthermore, $1 substitutes the first regex pattern, $2 the second regex pattern, and so on.

If you want to redirect specific requests made by Googlebot or Bingbot (the crawlers used to index pages on Google and Bing search engines), you can use the following code:


RewriteCond %{HTTP_USER_AGENT} .*(Googlebot|Bingbot).*
RewriteRule ^(.*?)/abc $1 [R=301]



This is useful if you want to omit specific pages from being indexed (such as administrator or user profiles). In this case if Googlebot or Bingbot try to access http://www.r00tb0x.com/abc they will be redirected back to http://www.r00tb0x.com.

Another popular use of URL rewriting is to make SEO friendly URLs. As you may know, websites in the form http://www.r00tb0x.com/?page=123456 are not ranked properly by Google as they lack keywords. A more SEO friendly URL would be http://www.r00tb0x.com/content/apache-rewrites-101 since the URL name contains keywords specific to the content of the page. In order to convert URL variables to SEO friendly names, one can use the following code:

RewriteCond %{QUERY_STRING} ^uuid=123$
RewriteRule ^(.*?) $1/123? [R=301]




This will redirect requests from http://www.r00tb0x.com/?uuid=123 to http://www.r00tb0x.com/123
Post a Comment