【问题标题】:Nginx Strip URL ParametersNginx 去除 URL 参数
【发布时间】:2021-08-03 16:14:01
【问题描述】:

我想在发送到 proxy_pass 之前去掉 url 参数

对于访客请求网址: => https://example.com/?wanted1=aaa&unwanted1=bbb&unwanted2=ccc&wanted2=ddd

然后它将所有不需要的参数剥离为: => https://example.com/?wanted1=aaa&wanted2=ddd

我现在的方式是这样的:

if ($args ~ ^(.*)&(?:unwanted1|unwanted2)=[^&]*(&.*)?$ ) {
    set $args $1$2;
}

但它只删除 1 个参数并且从不进行递归。如何解决这个问题?我想修改 $args。

【问题讨论】:

标签: regex nginx


【解决方案1】:

如果您想要递归,您可以在 location 块中使用 rewrite...last。 Nginx 在产生内部服务器错误之前只会容忍少量的递归(可能是十次迭代)。

例如:

location / {
    if ($args ~ ^(?<prefix>.*)&(?:unwanted1|unwanted2)=[^&]*(?<suffix>&.*)?$ ) {
        rewrite ^ $uri?$prefix$suffix? last;
    }
    ...
}

请注意,您需要使用命名捕获,因为在评估 rewrite 语句时会重置编号的捕获。

请注意,rewrite 需要尾随 ? 以防止将现有参数附加到重写的 URI。详情请见this document

【讨论】:

  • 它几乎可以工作了。只是一个小问题: hxxps://example.com/tester.php?unwanted1=111&unwanted2=222&unwanted2=222 将被重写为 hxxps://example.com/tester.php?unwanted1=111 所以我们的“不需要的参数”将如果它放在第一位,就不会被剥夺。
  • 您的正则表达式当前需要在不需要的参数前加上&amp;。试试看:^(?:(?&lt;prefix&gt;.*)&amp;)?(?:unwanted1|unwanted2)=[^&amp;]*(?&lt;suffix&gt;&amp;.*)?$
猜你喜欢
  • 1970-01-01
  • 2016-05-20
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多