Search code examples
phpapachehttp-redirecthttp-status-code-301mod-alias

HTTP redirect one URL to another based on query string


When the URL /page1.php?abc is requested, I want it redirected to /page1.php?xyz instead.

Specifically, this is what I want to tell the client:

HTTP/1.1 301 Moved Permanently
Location: /page1.php?xyz

I've tried Apache RedirectMatch directive, but it doesn't seem to support query strings.

Is there another directive which supports HTTP-redirect for URLs with query strings?

Currently I'm accomplishing this using PHP's header function, but this feels like a stopgap hack so I'm looking for an Apache solution.


Solution

  • You can use mod_rewrite for this. If this module is available you use these rules (must be placed inside /.htaccess):

    RewriteEngine on
    RewriteCond %{QUERY_STRING} ="abc"
    RewriteRule ^page1\.php$ /page1.php?xyz [R=301,L]
    

    There is a PHP-only solution too:

    if ($_SERVER["QUERY_STRING"] == "abc") {
        header("Location: /page1.php?xyz", true, 301);
        die;
    }