views:

150

answers:

2

In my MVC application I use a uri router than determines which controller and action to use and detects GET parameters from the uri. I've written it so that it will accept both these forms:

http://localhost/controller/action/param1Name/param1Value
http://localhost/controller/action?param1Name=param1Value

Now what I'd like to do is use mod_rewrite to redirect the ?p=v form to the /p/v form (reasoning is purely cosmetic, GET forms use the ?x=y form). I'm completely stuck with how I'd do this however - I have an idea I need to use ${QUERY_STRING} but I'm not sure how.

+1  A: 

If you're doing it for cosmetic reasons you may want to do a POST instead, and then the query params will not be shown in the URL.

If not - I'd like to see the answer to this one myself!

Supertux
If it can't be done then yeah I'll take this approach. Would still be nice if it's possible though.
Ross
+2  A: 

If you really want to redirect requests of the form /controller/action?param1Name=param1Value to /controller/action/param1Name/param1Value, try this:

RewriteCond %{THE_REQUEST} ^GET\ /[^/]+/[^/]+\?[^\s]+
RewriteCond %{QUERY_STRING} ^([^=&]+)=([^&]+)&?(.*)
RewriteRule ^[^/]+/[^/]+.* /$0/%1/%2?%3 [N]
RewriteCond %{THE_REQUEST} ^GET\ /[^/]+/[^/]+\?[^\s]+
RewriteRule ^[^/]+/[^/]+.* /$0 [L,R=301]

But if you want to opposite way:

RewriteRule ^([^/]+/[^/]+)/([^/]+)/([^/]+)(/.*) $1$4?$2=$3 [QSA]
Gumbo
That's some crazy regex-fu :) It doesn't seem to work for me though - the GET params in the url stay as they are.
Ross
@Ross: Ok, now it’s tested and it works for me.
Gumbo
It still doesn't want to work on my platform but if it's working for you I'll mark it as answered. I decided to change where I use a form into some hyperlinks anyway). Thanks
Ross
You might want to use mod_rewrite’s logging function to see where it breaks. See http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteloglevel
Gumbo