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?

MrWhite
  • 11,643
  • 4
  • 25
  • 40
nate
  • 207
  • 1
  • 3
  • 9

2 Answers2

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]
Shane Madden
  • 112,982
  • 12
  • 174
  • 248
  • Something very similar to this is what I ended up using. Thanks! – nate Apr 23 '13 at 15:48
  • 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. – MrWhite Dec 12 '20 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

ETL
  • 6,443
  • 1
  • 26
  • 47
  • Thanks, but Apache's [docs](http://httpd.apache.org/docs/current/mod/directive-dict.html) on nomenclature don't specify whether the URL-path includes the query string or not. – nate Apr 19 '13 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. – ETL Apr 19 '13 at 15:48