RedirectMatch and Query String

11,061

Solution 1

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]

Solution 2

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

Share:
11,061

Related videos on Youtube

nate
Author by

nate

Updated on September 18, 2022

Comments

  • nate
    nate almost 2 years

    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?

  • nate
    nate about 11 years
    Thanks, but Apache's docs on nomenclature don't specify whether the URL-path includes the query string or not.
  • ETL
    ETL about 11 years
    That's what PATH means. There are various parts to a URL, the path and the query-strings are two parts.
  • nate
    nate about 11 years
    Something very similar to this is what I ended up using. Thanks!
  • MrWhite
    MrWhite over 3 years
    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.