I want to redirect:
https://www.example.com/?p2 to https://www.example.com/
https://www.example.com/?p1=v1&p2&p3=v3 to https://www.example.com/?p1=v1&p3=v3
https://www.example.com/page.php?p4=v4&p2 to https://www.example.com/page.php?p4=v4
You can assume that the query string missing the value is always p2, if that makes it easier to answer the question.
But the p2 query string will not always be missing the value, and I wouldn't want it removed in those cases.
.htaccessYou could do this in .htaccess with a bunch of re-writes in a bunch of different ways...
Example 1:
RewriteCond %{QUERY_STRING} ^p2$
RewriteRule . / [QSD,L]
RewriteCond %{QUERY_STRING} ^(.+)&p2$
RewriteRule . /?%1 [L]
RewriteCond %{QUERY_STRING} ^p2&(.+)$
RewriteRule . /?%1 [L]
RewriteCond %{QUERY_STRING} ^(.+)&p2(&.+)$
RewriteRule . /?%1%2 [L]
Example 2:
RewriteCond %{QUERY_STRING} (^|.*&)p2(&.*|$)
RewriteRule . /?%1%2 [L]
// This doesn't give particularly clean query strings (not that they need to
// be for the server to understand it).
// e.g.
// ?p1=v1&p2&p3=v3 -> ?p1=v1&&p3=v3
Example 3:
RewriteCond %{QUERY_STRING} (^|.*&)p2(?:&(.*)|$)
RewriteRule . /test.php?%1%2 [L]
// ?p2&p3=v3 -> ?p3=v3
// ?p1=v1&p2 -> ?p1=v1
// ?p1=v1&p2&p3=v3 -> ?p1=v1&p3=v3
"This also makes use of a mod_rewrite "feature", where a trailing & on the resulting query string is automatically truncated/removed before being assigned to the Location HTTP response header." @MrWhite
As @MrWhite points out a trailing & is truncated so having given this some more thought you could use the above as a one line condition to catch all possibilities (example input and output provided in commented lines //...).
Whilst you can change the query string as shown above there's really no point messing about doing so when you can so easily deal with it in your script (e.g. PHP):
if(empty($_GET["p2"])){
unset($_GET["p2"]);
}
Which you have to do anyway to process the query string on your page?!
Additional note
The rules above silently remove the query string. If you want the user to know then you should redirect as per @MrWhite's answer setting the flag [R=30X] with the appropriate HTTP response code:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With