我要重定向:
https://www.example.com/?p2
到https://www.example.com/
https://www.example.com/?p1=v1&p2&p3=v3
到https://www.example.com/?p1=v1&p3=v3
https://www.example.com/page.php?p4=v4&p2
到https://www.example.com/page.php?p4= v4
您可以假设缺少值的查询字符串始终是 p2
,如果这样可以更轻松地回答问题。
但是 p2
查询字符串不会总是缺少值,在这些情况下我不希望它被删除。
最佳答案
在 .htaccess
中修复
您可以在 .htaccess
中以多种不同的方式进行大量重写...
示例 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]
示例 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
示例 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
正如 @MrWhite 指出的那样,尾随的 &
被截断了,所以考虑到这一点后,您可以将上面的内容用作单行条件来捕获所有可能性(示例输入和输出在注释行 //...
) 中提供。
在脚本中修复
虽然您可以如上所示更改查询字符串,但是当您可以在脚本(例如 PHP
)中轻松处理它时,这样做真的没有意义:
if(empty($_GET["p2"])){
unset($_GET["p2"]);
}
您必须执行哪些操作才能处理页面上的查询字符串?!
补充说明
上面的规则默默地删除了查询字符串。如果您想让用户知道,您应该根据 @MrWhite 的 答案重定向,并使用适当的 HTTP 响应代码设置标志 [R=30X]
:
关于regex - htaccess : remove URL parameter from query string with missing value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65109758/