PDA

View Full Version : Mod rewrite for beginners -Apache-


seomike
06-03-2004, 03:54 PM
Might as well kick start this forum with some good info :)

Here is just some basic info for doing a mod rewrite for a simple dynamic site. These could include shopping carts, CMS, Blogs, Forums and more.

First thing that needs to happen is we'll have to open the source code of the file that is outputting the dynamic URL string.

Let's say we have a shopping cart and the url string is something like:
http://www.domain.com/catalog.php?item=shirt

The variable shirt is being generated by a database variable and the coding may look something like this.

echo '<a href="catalog.php?item='.$db_var["item"].'">link text</a>';

So let's go ahead and change this to out put as if it were a static page with a .html extension instead of .php.

echo '<a href="catalog/'.$db_var["item"].'\.html">link text</a>';

Alright our url string will look like this now http://www.domain.com/catalog/shirt.html

Now that we've solved the coding issue on the page we need to go tell the server to pick up this change. A mod rewrite acts like a translator it uses Regular Expressions to find string or character matches. If you're not savvy on your Regular Expressions check out this little site here (http://etext.lib.virginia.edu/helpsheets/regex.html).

We put all the mod rewrite code in the .htaccess file. So let's kick start our mod engine and get this working :)

#begin mod rewrite
RewriteEngine On
Options +followsymlinks
RewriteBase /

# rewrite static to dynamic
RewriteRule ^catalog/(.*)\.html$ /catalog.php?item=$1

#end mod

If we translate this into english :) What this code is saying is start looking for any character between catalog/ and .html. If you find those characters save them as a varaible and then parse the query using the stored variable as the value for item=. Pretty simple

Definitions:
^ = Start matching at the begining
$ = stop matching
. = any single character
* = quantifier that means match 0 or more times
( ) = anything in bracets will be stored as a variable
$1 = variable of the first ( )

Note: the above rewrite rule is a newbie way of doing it. If you know that a variable is only going to be letters or only going to be numbers you can substitute the (.*). Here are some suggestions

for just:
lower case letters = ^catalog/([a-z]+)\.html$
upper case letters = ^catalog/([A-Z]+)\.html$
both lower and upper = ^catalog/([a-zA-Z]+)\.html$
numeric = ^catalog/([0-9]+)\.html$

If you know the legth of the number (4000 = 4 in length) you can use quantifiers to dictate the result.

1 number long = ^catalog/([0-9]{1})\.html$
1 to 5 numbers long = ^catalog/([0-9]{1,5})\.html$

Hope this helps

Mikkel deMib Svendsen
06-07-2004, 07:32 AM
Thanks a lot for this and your other tutorials. Great work - I am sure a lot of people will find this very usefull