views:

320

answers:

2

I would like to rewrite something like:

http//www.example.com/index.php?var1=val1&var2=val2&var3=val3

Into

http://www.example.com/var1/val1/var2/val2/var3/val3/

I'm looking for a solution to work on an arbitrary number of variables. Can it be done?

+2  A: 

Take a look at this question: Can mod_rewrite convert any number of parameters with any names?

My answer can be used in your case too:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
for ($i=0, $n=count($segments); $i<$n; $i+=2) {
    $_GET[rawurldecode($segments[$i])] = ($i+1 < $length) ? rawurldecode($segments[$i+1]) : null;
}

And the corresponding rule to that:

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

This rule rewrites any request, that can not be mapped to an existing file or directory, to the index.php.

Gumbo
Glomek
Most misunderstand how mod_rewrite works or misstate what they are looking for: “I have URLs like /index.php?foo=bar and want /foo/bar.” But in most cases the are looking for the exact difference.
Gumbo
A: 

Yes. The trick is to write a RewriteRule that replaces one character (equals sign or ampersand) with a slash, and then use the "next" flag which restarts the rewrite process.

The following might be a good place to start:

RewriteRule ^/index.php - [chain]
RewriteRule ^(.*)[=&](.*)$ $1/$2 [next]
RewriteRule ^/index.php\? "/"

If I got this right, the first rule will do nothing, but only match if the path starts with "/index.php". The "chain" option means that the second rule won't run unless the first rule matches. The second rule will try to replace an = or & with a /, and if it succeeds, it will restart the entire rewriting process. The third rule, which will only be reached after all of the = and & have been replaced, will remove the "/index.php?" at the beginning.

Glomek