views:

227

answers:

1

I want to be able to take a URL like:

http://www.example.com/valOne/valTwo/valThree/valFour/valFive

and convert it to:

http://www.example.com/index.php?one=valOne&two=valTwo&three=valThree&four=valFour&five=valFive

I really only need a few query parameters for my application so the Regular Expression could have these five hard coded, but it would be nice if it could dynamically create new query parameters as additional 'folders' are added to the URL. Additionally, not all five folders or QPs will always be present, so it must be able handle that appropriately.

+3  A: 

Here’s a mod_rewrite rule that meets your needs:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?$ index.php?one=$1&two=$2&three=$3&four=$4&five=$5

But it would be certainly easier if you parse the requested URI path with PHP instead:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php

$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
var_dump($segments);
Gumbo
Thanks this works great! One question what does this do:RewriteCond %{REQUEST_FILENAME} !-f??
macinjosh
It checks if the requested URI can be mapped onto an existing file (`-f`). If so, the rule is not applied. Otherwise every URI would be redirected to `index.php` (even `index.php` itself as it also would be matched by `[^/]*`). See http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond
Gumbo