regex - htaccess : remove URL parameter from query string with missing value?

标签 regex .htaccess mod-rewrite query-string

我要重定向:

  • https://www.example.com/?p2https://www.example.com/

  • https://www.example.com/?p1=v1&p2&p3=v3https://www.example.com/?p1=v1&p3=v3

  • https://www.example.com/page.php?p4=v4&p2https://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]:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

关于regex - htaccess : remove URL parameter from query string with missing value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65109758/

相关文章:

.htaccess - 仅允许通过 .htaccess 直接访问特定文件夹名称

regex - Apache RewriteRule - 无法匹配字符串的开头

apache - 使用mod_rewrite提供网页的移动版本

regex - Htaccess 更改 php 扩展名

javascript - ng-repeat 内项目的正则表达式

python - 查找可能后跟小数点的所有数字

java - 正则表达式密码验证添加下划线,如特殊符号

.htaccess - 向 URL 添加尾部斜杠时获取 301 而不是 404

php - htaccess 301 重定向 - 删除查询字符串

mysql - MySQL 中带整数的逗号分隔列表 REGEX