3

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?

Paul Grigoruta
  • 2,386
  • 1
  • 20
  • 25
  • As you accepted my answer, I think you should edit your question and change the URLs. Because my solution rewrites requests of the second form internally to the first form. – Gumbo May 21 '09 at 14:54

2 Answers2

4

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.

Community
  • 1
  • 1
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • This does the reverse of what was requested. It turns "/a/b/c/d" into "/index.php?a=b&c=d". The question asked about turning "/index.php?a=b&c=d" into "/a/b/c/d". – Andru Luvisi May 21 '09 at 14:54
  • 1
    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 May 21 '09 at 15:11
0

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.

Andru Luvisi
  • 24,367
  • 6
  • 53
  • 66