Using mod rewrite to create virtual directories

We all like mod rewrite and the clean urls that it gives but what if you are starting out with this whole rewirte stuff and you want to integrate it into your web application? well there are some simeple ways to test out what arguments a rewritten url is going to pass to youer php script. Too test this out you could create a script similar to the following;

<?php
$dir1=$_GET['dir1'];
$dir2=$_GET['dir2'];
$file=$_GET['file'];
$fid=$_GET['id'];
# echo results
echo $dir1."\n<br />";
echo $dir2."\n<br />";
echo $file."\n<br />";
echo $fid."\n<br />";
?>

perhaps you could call it values.php, then in the same directory as values.php create (or edit) a .htaccess file which contains the following;


RewriteEngine On
RewriteRule ^([a-z0-9_-]+)/([a-z0-9_-]+)/([a-z0-9_-]+)_id([0-9]+)/index.html$ values.php?dir1=$1&dir1=$2&file=$3&id=$4 [L]

^ indicates the start of the rule
([a-z0-9_-]+) means that for the directories any character from a to z, any number, hyphans (-) and underscores (_) are allowed.
/ indicates that this part of the rule ends when a forward slash is found the same deal with the “_id” part.
([0-9]+) indicates any number

once this is all setup assuming that apache and php are setup correctly, you can test this rule by entering the url into firefox, for example;

http://localhost/test-dir1/test-dir2/filename_id1024/index.html you would have to write additional rules for any other url formats. if you wanted to use this with a database you should probably store the directories (categoires) sefurl value so that you could use $query = “SELECT * FROM tablename WHERE sefurl = ‘$sane_dir1′”; to get information on that category, this of course falls flat on it’s face if two categories have the same name to solve this you could use the category id in the url or just simply avoid creating categories with identical names. Any question or errors (well I haven’t tested this properly) please comment, thanks. Lee

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

If you want to leave a feedback to this post or to some other user´s comment, simply fill out the form below.

(required)

(required)


Security Code: