6

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?

2 Answers 2

10

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] 
2
  • Something very similar to this is what I ended up using. Thanks! Commented Apr 23, 2013 at 15:48
  • 1
    For other readers who are using .htaccess (or in a directory context), you'll need to remove the slash prefix on the RewriteRule pattern, ie. ^redirect\.php$. Because when used in .htaccess the URL-path matched by the RewriteRule pattern is less the directory-prefix, it's not the full URL-path. Commented Dec 12, 2020 at 10:31
1

According to the documentation, it matches against URL:

The supplied regular expression is matched against the URL-path

http://httpd.apache.org/docs/current/mod/mod_alias.html#redirectmatch

Every URL consists of the following: the scheme name (commonly called protocol), followed by a colon, two slashes, then, depending on scheme, a server name (exp. ftp., www., smtp., etc.) followed by a dot (.) then a domain name (alternatively, IP address), a port number, the path of the resource to be fetched or the program to be run, then, for programs such as Common Gateway Interface (CGI) scripts, a query string, and an optional fragment identifier.

http://en.wikipedia.org/wiki/Uniform_Resource_Locator (section Syntax)

You can do that with RewriteRule

2
  • Thanks, but Apache's docs on nomenclature don't specify whether the URL-path includes the query string or not. Commented Apr 19, 2013 at 15:41
  • 1
    That's what PATH means. There are various parts to a URL, the path and the query-strings are two parts. Commented Apr 19, 2013 at 15:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.