Source Rally PHP Community Scripts .. Sign up .. Login
Here is my 3 minute guide on how I use mod_rewrite to make useful and pretty urls like http://www.sourcerally.net/regin/Scripts.

.htaccess file in root directory of the domain:
[code]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-F
RewriteRule .$ index.php
[/code]
The htaccess file sends all requests that would have ended up with a 404 error on to the file index.php (in the root directory).

Next in index.php I do following to handle these requests:
[code]
<?php
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$urlInfo = parse_url($url);
$_PATHS = explode('/',substr($urlInfo['path'],1));
?>
[/code]

If you try requesting domain.com/Dir0/Dir1/Dir2 - the $_PATHS array will look like this:
$_PATHS[0]=='Dir0'
$_PATHS[1]=='Dir1'
$_PATHS[1]=='Dir2'

Now you can use the global variable $_PATHS to determine which content to deliver, for instance this way:
[code]
<?php
switch($_PATHS[0])
{
    case 'Admin':
    //logic to fetch content for administration
    break;
    case 'Content':
    //logic to fetch content for administration
    break;
}
?>
[/code]

All $_GET variables will be unaffected by this rewrite.

I like doing it this way as you wont have to setup up a htaccess file in several directories or apply special rules to your htaccess file. However as you are using mod_rewrite and htaccess it drains extra power from your server - a small cost I am more than willing to take.

Comments:


delayedinsanity - 2008-04-30
Add to friends       Mail user
Seems like too much work to get $_PATHS. I do the same, but with one line;

$this->command = explode("/", $_SERVER['REQUEST_URI']);

Works for me. ;)

Sign up to add your own comment here!

All user contributed content is available under the unless specified otherwise.
Remaining copyrights Regin Gaarsmand 2006-2008
About www.SourceRally.net