Introduction to mod_rewrite and some basic examples

ModRewrite is a powerful feature of the Apache web server. It provides an easy way to modify/manipulate URLs. As complicated as it sounds a regular webmaster can benefit from this feature in many way. I will list here the ones I consider most useful for the regular webmaster.

Create easy to remember URLs or also known as COOL URIs, other call them Search Engine Friendly URLs. For example you have some complicated site driven by some server-side scripting language: PHP, Perl, etc. In general its URLs will look like

http://www.example.com/view.php?cat=articles&a=10&page=20&lang=en

It is not easy to remember such URL.

Using ModRewrite you can make the URL look like:

http://www.example.com/en/articles/10-2

Here is the code:

RewriteEngine On
RewriteRule ^([a-z]*)/([a-z]*)/([1-9]+)(-[1-9]+)? $ http://www.example.com/view.php?cat=$2&a=$3&page=$4&lang=$1 [L]

What the code does? It tries to match the requested URL against a regular expression string.
In case it finds a match it performs an internal rewrite. The user will never see the long URL in his browser.

Change enviromental variables
An example can be found here

The official ModRewrite documentation can be found at:
http://httpd.apache.org/docs/1.3/misc/rewriteguide.html

In the next several articles you will find some commonly used ModRewrite rules for performing everyday tasks.