Peter Lur
Peter Lur

Reputation: 758

RewriteCond: 2 parameters for QUERY_STRING

I am dealing with an API that is accessing an URL on my website and adding
/?parameter1=value&parameter2=value to the url. I want my htaccess to handle this request and only keep the parameter's values. The API is also adding many other parameters in the query string but I just want to keep two of them.

The following does not work:

RewriteCond %{QUERY_STRING} ^parameter1=([^&]+)
RewriteCond %{QUERY_STRING} ^parameter2=([^&]+)
RewriteRule ^my-url/?$ controller.php?parameter1=%1&parameter2=%2

How can I do that correctly?

EDIT:

Here is an example.

The url is:
http://example.com/my-url/?parameter1=value1&stuff=1&stuff2=2&parameter2=value2

The htaccess should get the parameter1 & parameter2 values.

Upvotes: 1

Views: 2135

Answers (3)

Jason
Jason

Reputation: 719

I've had to do a similar setup with key/value pairs in the GET which could come in any order depending on the client platform.

Based on useful pointers in this thread, this is what I came up with based on the question above:

#= 1. Catch parameter1, append querystring as "p1=". Rewrite to "/parameter1" below:
RewriteCond %{REQUEST_URI}  ^/my-url/$
RewriteCond %{QUERY_STRING} ^parameter1=([^&]+)
RewriteRule (.*) /parameter1?%{QUERY_STRING}&p1=%1 [P,QSD]

#= 2. Catch parameter2, append querystring as "p2=". Rewrite to "/parameter2" below:
RewriteCond %{REQUEST_URI}  ^/parameter1$
RewriteCond %{QUERY_STRING} ^parameter2=([^&]+)
RewriteRule (.*) /parameter2?%{QUERY_STRING}&p2=%1 [P,QSD]

#= 3. Now explicitly catch p1,p2 and feed to them to the back-end url:
RewriteCond %{REQUEST_URI}  ^/parameter2$
RewriteCond %{QUERY_STRING} p1\=([^&]+)&p2\=([^&]+)$
RewriteRule (.*) controller.php?parameter1=%1&parameter2=%2 [P,L,QSD]

The above works fine for me but I do notice it a tiny bit slow to process, so if anyone has any criticism then I would be glad to hear it!

Upvotes: 0

Howli
Howli

Reputation: 12469

Try the following:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /my-url/\?parameter1=(.*)&stuff=(.*)&stuff2=(.*)&parameter2=(.*)\ HTTP
RewriteRule ^ /controller.php?parameter1=%2&parameter2=%5\? [R,L]

Mind it will only get the two parameters if there are always &stuff=1&stuff2=2 those two values in the url.

Upvotes: 0

Panama Jack
Panama Jack

Reputation: 24448

Try this and just grab the two parameters in your server side code. e.g. $_GET. If they are always in the query string, you can just check for parameter1 and then it will append the other parameters and you can get what you need.

 RewriteCond %{QUERY_STRING} ^\bparameter1=
 RewriteRule ^my-url/?$ controller.php [QSA,L]

Upvotes: 2

Related Questions