URL Rewriting, A Simple Example

Eoin | REST, Regular Expressions, WebServices, mod_rewrite | Wednesday, May 23rd, 2007

One of the tools I used to construct the train time table service was mod_rewrite.

mod_rewrite can change URLs on the fly based on any rewriting rules you want to apply.

so instead of
../trains/Trains.php?from=Cork&to=Cobh
we now have
../trains/Cork/Cobh

Much nicer isn’t it.

Rewriting allowed me to create a URL structure which hides the implementation details, is easy to remember and can be constructed easily.
The URL is also more RESTful as a particular URL refers to a particular resource, todays time table.
An added bonus of hiding the implementation details makes it more secure.

Using mod_rewrite is straight forward.

First of all, the mod_rewrite is usually installed by default with Apache so you shouldn’t to worry about that.

Next, if like me you don’t have control over the server then you’ll have to use a .htaccess file which can be placed in the folder you do have access to. In this case I placed the .htacces file in the ../trains folder.
An advantage of placing the .htaccess file in a sub-folder is that it won’t have an effect on your root folder or any other of its subfolders, The .htaccess file will only effect the folder it is placed in.

Next we need to add some stuff to .htaccess file

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/?$ /trains/trains.php?from=$1&to=$2 [L,NC]
RewriteRule ^/?$ /trains/trains.php [L,NC]

The first line activates the rewrite engine.
The next lines are where the magic happens,
it is in the format Command Pattern Substitution Flags

Command : Simply “RewriteRule”
Pattern : This is the Regular Expression to matched in the URL, If a match is found then the rule is applied.
Substitution : This is the replacement string that the will replace the part of the URL matching the pattern if any.
Flags : You can set flags affect the behavior of mod_rewrite, in this case L and NC. L means last rule, if a match is found do not apply any further URL rewrites. NC means Not Case Sensitive.

Now just save the changes and we’re done.

The rewrite rule RewriteRule ^([^/]*)/([^/]*)/?$ /trains/trains.php?from=$1&to=$2 [L,NC] will rewrite URLs of the format ../trains/Depart/Destination/ to ../trains/Trains.php?from=Depart&to=Destination

The second rewrite rule RewriteRule ^/?$ /trains/trains.php [L,NC] will rewrite URLs of the format ../trains/ to ../trains/Trains.php as long as the first rule wasn’t triggered by a matching pattern being found.

The rewriting of URLs is completely invisible to the user and they will only the simplified URL.

To get the must out of mod_rewrite you’ll need to understand regular expressions, just one more reason why developers should add regular expressions to their toolbox.

There are a number of mod_rewrite clones available for IIS so URL rewriting is not just for Apache, It’s for life.

mod_rewrite URL Rewriting Engine.

Powered by WordPress | Theme by Roy Tanck