What we do in life echoes in eternity!
Home About Me Diary

Apache mod_rewrite examples

posted on: 20:27, October 26th , 2007

A slightly more complicated mod_rewrite example

Let’s try a slightly more meaty example now. Suppose you have a web page which takes a parameter. This parameter tells the page how to be displayed, and what content to pull into it. Humans don’t tend to like remembering the additional syntax of query strings for URLs, and neither do search engines. Both sets of people seem to much prefer a straight URL, with no extra bits tacked onto the end.

In our example, you’ve created a main index page with takes a page parameter. So, a link like index.php?page=software would take you to a software page, while a link to index.php?page=interests would take you to an interests page. What we’ll do with mod_rewrite is to silently redirect users from page/software/ to index.php?page=software etc.

The following is what needs to go into your .htaccess file to accomplish that:

RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]

Let’s walk through that RewriteRule, and work out exactly what’s going on:


Sees whether the requested page starts with page/. If it doesn’t, this rule will be ignored.

Here, the enclosing brackets signify that anything that is matched will be remembered by the RewriteRule. Inside the brackets, it says “I’d like one or more characters that aren’t a forward slash or a period, please”. Whatever is found here will be captured and remembered.

Makes sure that the only thing that is found after what was just matched is a possible forward slash, and nothing else. If anything else is found, then this RewriteRule will be ignored.

The actual page which will be loaded by Apache. $1 is magically replaced with the text which was captured previously.

Tells Apache to not process any more RewriteRules if this one was successful.


Write a comment

*Security code:
*1+2 = (write in words ;)

All materials on this site are licensed under the following license: "Steal every piece of information you can get your hands on and run as fast as you can "