apache.htaccesshttp-redirectmod-rewritemod-alias

htaccess Redirect Single Page to Different Domain without Parameters


I have a site with the following htaccess file:

RewriteCond %{THE_REQUEST} \s/+(.+?)\index.html/?[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?uri=$1 [NC,L,QSA]

There are two pages that I need to redirect to a different domain. Currently I have them setup as 302 redirects with the following line:

Redirect 302 /some-url-slug https://example.com/some-new-url-slug

This does work to redirect to the new domain but the issue is it's adding the uri parameter to the redirected url so I get something like:

https://example.com/some-new-url-slug?uri=some-url-slug

I thought adding it above the rewrite rule would solve it, but it does not. How can I omit that rule but only for 2 specific pages?


Solution

  • I thought adding it above the rewrite rule would solve it

    The Redirect directive belongs to mod_alias, the other directives are mod_rewrite. It doesn't matter where you place the Redirect directive, it will always be processed after mod_rewrite. And the Redirect directive will preserve the query string.

    You need to use a mod_rewrite RewriteRule instead, at the top of the file, for these two specific redirects. For example:

    RewriteRule ^some-url-slug$ https://example.com/some-new-url-slug [QSD,R=302,L]
    

    Note that the URL-path matched by the RewriteRule directive does not start with a slash. The QSD (Query String Discard) flag ensures that any query string that might be present on the initial request is discarded (otherwise it is passed through by default).

    UPDATE:

    I just realized that adding a trailing / to the url loads the original page. Do I need to create a seperate redirect rule for links that have the trailing slash?

    You can include this in the same rule and make the trailing slash optional with the addition of /? at the end of the pattern. For example:

    RewriteRule ^some-url-slug/?$ https://example.com/some-new-url-slug [QSD,R=302,L]
    

    This now matches both some-url-slug or some-url-slug/ and redirects to the URL as before.