views:

98

answers:

3

Hey guys, here's what I'm attempting:

I'd like to make it so I can turn all url variables and values into folders, all with one rule. I was expecting to find some way to do this:

www.example.com/var1/val1/var2/val2/varN/valN

In an ideal world I could get rewrite to this:

www.example.com/index.php?var1=val1&var2=val2&varN=valN

But I'm also happy to do something like this:

www.example.com/index.php?path=/var1/val1/var2/val2/varN/valN

And then work them into an array or structure in PHP. In my case everything works through index.php so that's a constant.

Is there any way to do this? I can't find anything through google and apparently I can't figure it out for myself!

Thanks guys :-)

A: 

This is something copied almost verbatim from a <Directory> directive in my main apache config. I have been unable to do so, but ought to work in .htaccess as well (probably without the <Directory> parts).

<Directory /path/to/document/root/>
    RewriteEngine On
    RewriteRule ^(.*)$ index.php?path=$1 [QSA]
</Directory>

The URL http://www.any.com/foo/bar/baz/spam/eggs should become http://www.any.com/index.php?path=/foo/bar/baz/spam/eggs

GameFreak
A: 

Try this rule:

RewriteEngine on
RewriteRule !^index\.php$ index.php?path=%{REQUEST_URI} [L]

That will rewrite any request except for index.php to index.php.

And if you want to exclude existing files and directories, add these RewriteCond directives to your rule:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^index\.php$ index.php?path=%{REQUEST_URI} [L]

And here’s a rule for the former format, except that the parameters have the form var[]:

RewriteRule ^([^/]+)/([^/]+)(.*)$ /$3?$1[]=$2 [N,QSA]
Gumbo
A: 

Gumbo, I'm really liking this solution, it works perfectly:

RewriteRule ^([^/]+)/([^/]+)(.*)$ /$3?$1[]=$2 [N,QSA]

I get the feeling I need to stick something like !(js|css) in there to exclude those folders, but I can't figure out where, I've tried a couple places to no avail. Do you have a tweak for that? Thanks again for the killer solution!

Edit: I figured it out, or found it rather! I put this before the rewrite rule:

RewriteCond %{REQUEST_FILENAME} !^(.+).css$

RewriteCond %{REQUEST_FILENAME} !^(.+).js$

Finally, it looks like this, and works perfectly:

RewriteCond %{REQUEST_FILENAME} !^(.+).css$

RewriteCond %{REQUEST_FILENAME} !^(.+).js$

RewriteRule ^([^/]+)/([^/]+)(.*)$ /$3?$1[]=$2 [N,QSA]

My favorite aspect of this solution is that I can pass url arrays, so:

www.any.com/var1/val1/var1/val2/

Actually creates

$var1= array("val1","val2");

Aaron