【问题标题】:Remove part of URL using Nginx with Proxy Pass使用 Nginx 和 Proxy Pass 删除部分 URL
【发布时间】:2021-04-19 17:52:35
【问题描述】:

我正在通过 nginx 运行一个 Web 应用程序,我需要删除部分 URL (?debug),只要它可能出现,例如:

https://example.com/web?debug#menu=accounts

https://example.com/web?debug#menu=orders

https://example.com/web#menu=accounts

https://example.com/web#menu=orders

我的 nginx 配置文件有以下位置块:

    location / {
            proxy_pass      http://example.com;
    }

我在网上查看了实现此目的的方法,但没有任何效果。我尝试了以下方法,但 url 是按原样传递的,没有任何变化:

    location ^~ \?debug# {
           if ($request_uri ~* "\?debug#(.*)") {
                    rewrite ^\?debug(.*)$ $1 break;
                    proxy_pass  http://example.com/$1;
           }
    }

    location / {
            proxy_pass      http://example.com;
    }

任何帮助将不胜感激。

【问题讨论】:

  • ?debug 是查询字符串。它不是用于匹配locationrewrite 命令的规范化URI 的一部分。您要删除查询字符串,还是只删除包含单词debug 的查询字符串?
  • 感谢您的回复。我想删除任何只有单词 debug 的查询字符串。即 example.com/web?debug#menu=orders 必须更改为 example.com/web#menu=orders 但可以允许 example.com/web?debug=files#menu=orders 按原样通过。我希望能澄清它。
  • 你可以试试:if ($args = "debug") { rewrite ^(.*)$ $1? last; }
  • @RichardSmith 试过了,它仍然没有变化。根据您之前的回答,“?debug”是一个查询字符串,我做了更多的挖掘,发现了这段代码 'if ($request_uri ~ "([^\?]*)\?(.*)debug([^& ]*)&?(.*)") { 设置 $args $2$4;重写 "^" $scheme://$host$uri 永久; }' 但这会删除它找到的所有 ?debug 实例。如果没有传递任何值,我想要只删除 ?debug 的东西。

标签: nginx


【解决方案1】:

我找到了解决问题的方法。这是代码。

    location / {

            set $test 0;

            if ($request_uri ~ "([^\?]*)\?(.*)debug([^&]*)&?(.*)") {
                    set $test 1;
            }

            if ($request_uri ~ "([^\?]*)\?(.*)debug=files([^&]*)&?(.*)") {
                    set $test 0;
            }

            if ($test = 1) {
                    set $args $2$4;
                    rewrite "^" $scheme://$host$uri;
            }

            proxy_pass      http://example.com;
    }

从这些链接的答案中获得更多帮助:

Nginx Redirect - Remove a specific query parameter from URL

How can I use an "or" operator in an nginx "if" statement?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2012-03-24
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多