Remove query string from 301 redirect URL

9,933

By default the query string on the requested URL is appended to the rewritten/redirected URL.

On Apache 2.4+ you should use the QSD (Query String Discard) flag on the RewriteRule directive in order to discard the query string from the redirected URL. For example:

RewriteCond %{QUERY_STRING} =p=15
RewriteRule ^seasonal/christmas$ /holiday-decor/christmas.html [QSD,R=301,L]

The RewriteCond directive is required in order to match the query string part of the requested URL. (The URL matched by the RewriteRule pattern is the URL-path only, which notably excludes the query string.) The = prefix on the CondPattern =p=15 indicates a literal "string" match (as opposed to a regex), so it matches p=15 exactly.

On Apache 2.2 and earlier you would instead need to append a ? at the end of the RewriteRule substitution, to remove the query string. This essentially writes a blank query string (the ? does not actually become part of the redirected URL). Note that by appending any query string on the substitution string you overwrite the query string on the request. (If you needed to also append the original query string in this situation then you need the QSA flag - Query String Append - but otherwise, this flag is not required.)

For example, on Apache 2.2, you would change the above RewriteRule directive to read:

RewriteRule ^seasonal/christmas$ /holiday-decor/christmas.html? [R=301,L]

NB: Appending the ? also works on Apache 2.4. Although using the QSD flag is preferred. The two methods are not identical.

Share:
9,933

Related videos on Youtube

mrblo0m
Author by

mrblo0m

Updated on September 18, 2022

Comments

  • mrblo0m
    mrblo0m over 1 year

    I'm having some trouble with redirects and I haven't been able to get this to work. I want to make the following

    http://www.example.com/seasonal/christmas?p=15
    

    redirect to

    http://www.example.com/holiday-decor/christmas.html
    

    I was wondering if someone could help me with the rewrite rule so the query string doesn't appear in the redirected URL. I'm using .htaccess with a Magento platform site.

  • MrWhite
    MrWhite about 9 years
    This does not answer the question or even work with the OPs example?! This particular example is intended to remove a particular segment (name/value pair) from a query string, whilst maintaining the rest of it.