Search code examples
.htaccessmod-rewritehttp-redirectquery-stringhttp-status-code-301

how to do a htaccess 301 redirect with query strings?


i have some links that i need to redirect, like:

/pass-help.php?action=1&[email protected] to /about/help
or
/contests/contest-a?testa=1&testb=1 /user/index/contest

i need a way to find the action or the email in the links above because they can be anything.

maybe something like /pass-help.php?action=(\?.+)&email=(\?.+) to /about/help

but im not sure how to write the query string.

any ideas?

if so, please explain a bit so i can understand what is happening.

thanks


Solution

  • If the query strings don't matter, you can just ignore them:

    via mod_alias:

    Redirect 301 /pass-help.php /about/help?
    Redirect 301 /contests/contest-a /user/index/contest?
    

    via mod_rewrite:

    RewriteRule ^/?pass-help\.php$ /about/help? [L,R=301]
    RewriteRule ^/?contests/contest-a /user/index/contest? [L,R=301]
    

    Note that in the mod_alias case, there will be a stary ? at the end. That's needed in order to get rid of the query string.

    If the query strings need to have some param names, but you don't care about the values:

    via mod_rewrite:

    RewriteCond %{QUERY_STRING} (^|&)action=
    RewriteCond %{QUERY)STRING{ (^|&)email=
    RewriteRule ^/?pass-help\.php$ /about/help? [L,R=301]
    
    RewriteCond %{QUERY_STRING} (^|&)testa=
    RewriteCond %{QUERY_STRING} (^|&)testb=
    RewriteRule ^/?contests/contest-a /user/index/contest? [L,R=301]
    

    If the query strings need to have some param names with EXACTLY some value:

    RewriteCond %{QUERY_STRING} (^|&)action=1
    RewriteCond %{QUERY)STRING{ (^|&)[email protected]
    RewriteRule ^/?pass-help\.php$ /about/help? [L,R=301]
    
    RewriteCond %{QUERY_STRING} (^|&)testa=1
    RewriteCond %{QUERY_STRING} (^|&)testb=1
    RewriteRule ^/?contests/contest-a /user/index/contest? [L,R=301]