views:

367

answers:

3

I'm quite experienced in PHP but I don't quite use mod_rewrite (although I should). All I want to ask is if it's possible to pass many variables through a single rewrite rule.

For example, is it possible to rewrite this:

localhost/test.php?id=1&name=test&var1=3

into this:

localhost/mysupertest/

and also use the same rewrite rule for different values?

localhost/test.php?id=5&name=another_name&var3=42

into

localhost/mysupertest/

I know it can be done using Ajax, cookie, session, or POST variables, but I really want to use GET variables.

A: 

Yes, it's possible. Anything you can match with your regex expression can be rewritten as any url. Anytime you put part of your regex string inside of parenthesis ( ), it becomes a variable that can be used while rewriting.

You would want something like (I think):

RewriteRule test.php\?id=[0-9]+&name=.+&var1=[0-9]+ mysupertest/

John
+1  A: 

Definitely possible. Something like this would do it:

RewriteRule test.php\?(.*)$ mysupertest/

However, you will lose your variables if you do that, as it's effectively the same thing as accessing localhost/mysupertest directly, with no query string data. If you want to keep the variables, perhaps in a REST-style url, you can use back-references to rewrite them. As John mentioned, a back-reference is simply a set of brackets, and whatever matches inside them becomes a variable in a numeric ordering scheme.

RewriteRule test.php\?id=(.*)&name=(.*)&var3=(.*)  mysupertest/$1/$2/$3

With the above rule, accessing test.php?id=567&name=test&var3=whatever would be the same as accessing mysupertest/567/test/whatever

zombat
+1  A: 

I'm not exactly sure what you're asking for, but you probably should be using the [QSA] option for mod_rewrite, which will append all the URL parameters from '?' onwards. For example:

RewriteRule ^mysupertest/? test.php [QSA]

Take a look at this question for more details.

too much php