Alex
Alex

Reputation: 12433

RewriteCond match for certain Query param/value pair

I have to do a redirect to another host if a certain parameter/value pair is in the querystring.

So far I have

RewriteCond %{REQUEST_URI}?%{QUERY_STRING} [&\?]abc=23&?
RewriteRule ^(.*)$ http://anotherserver.com/$1 [R,NC,L]

that works for:

/index.php?id=95&abc=23
/index.php?abc=23&id=95
/index.php?id=95&abc=23&bla=123

but it also matches /index.php?id=95&abc=234 for example.

I need a pattern that matches exactly abc=23, no matter where it occurs.

Any suggestions on this? :-)

Upvotes: 2

Views: 3549

Answers (2)

Andrew
Andrew

Reputation: 6351

The question mark makes the preceding token in the regular expression optional. E.g.: colou?r matches colour or color.

RewriteCond %{REQUEST_URI}?%{QUERY_STRING} [&\?]abc=23&?

You are matching abc=23& OR abc=23 with the rest of the string unconstrained so abc=234 is a valid match. What you really want is & or nothing else. I'm not sure if this RegExp is legal in Apache but it would be written as:

RewriteCond %{REQUEST_URI}?%{QUERY_STRING} [&\?]abc=23(&|$)

Here are the test cases I used at my favourite online RegExp tester:

abc=23&def=123
abc=234
abc=23

Upvotes: 1

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

I'd try this regex (&|^)abc=23(&|$) and match is only against %{QUERY_STRING}.

Upvotes: 7

Related Questions