views:

62

answers:

1

I'm doing some URL rewriting and I can accomplish what I need to do with the following:

RewriteRule ^([^/]*)/([^/]*)$ index.php?arg1=$1&arg2=$2 [L,QSA]
RewriteRule ^([^/]*)$ index.php?arg1=$1 [L,QSA]

You get what I'm trying to do here, I basically want to take the full url and parse it into individual arguments. So /blah/test/asdf/hi would come in as arg1=blah, arg2=test, etc.

Now, if I want to expand this to 4 or 5 arguments, I'm wondering if there's a cleaner way to present it rather than going out with ?arg1=$1&arg2=$2&arg3=$3 etc. etc. I've seen people do this programatically (just take whole string with slashes and parse it in code) but I was curious if there was a way to do it with apache.

+1  A: 

You can use PHP to do that:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$pathSegments = array_map('rawurldecode', explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1)));

The first line is to get just the URL path from the request URL. The other line will remove the leading slash (substr), split into the segments (explode) and decode each segment (array_map with rawrurldecode).

Now you just need to pass all request to your index.php:

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

The additional condition will exclude requests that can be mapped to existing files.

Gumbo
Thanks for illustrating the programmatic approach that I mentioned. It looks like that's the way it'll have to be done if I want this flexibility.
epalla
@epalla: Yes, absolutely. Your application knows best how to interpret the URLs. So it should do the URL interpretation as well and not mod_rewrite.
Gumbo