Apache RedirectMatch – Handling Query Strings with RedirectMatch

apache-2.2mod-aliasmod-rewritequerystringredirect

Compare these two RedirectMatch's. The first doesn't work:

RedirectMatch 302 ^/redirect\.php[?]page=(.+)$ http://somewhereelse.com/$1

Versus this, which will redirect to http://somewhereelse.com/?page=wherever:

RedirectMatch 302 ^/redirect\.php([?]page=.+)?$ http://somewhereelse.com/$1

Does RedirectMatch only match the URI and not the query string? Apache's documentation is a bit vague in this area. What I'm trying to do is extract the page query parameter and redirect to another site using it.

Is that possible with RedirectMatch or do I have to use RewriteCond + RewriteRule?

Best Answer

It's not possible to use RedirectMatch in this case unfortunately; the query string is not part of URL string that RewriteMatch is compared to.

The second example works because the query string the client sent is re-appended to the destination URL - so the optional match is matching nothing, the $1 replacement is an empty string, but then the client's original query string is stuck back on.

A RewriteCond check against the %{QUERY_STRING} will be needed instead.

RewriteCond %{QUERY_STRING} page=([^&]+)
RewriteRule ^/redirect\.php$ http://somewhereelse.com/%1? [R=302,L]
Related Topic