【问题标题】:Location Regex and ProxyPass Regex for NGINX confNGINX conf 的位置正则表达式和 ProxyPass 正则表达式
【发布时间】:2021-12-11 07:02:24
【问题描述】:

想知道是否有办法将我的 nginx.conf 文件配置为使用正则表达式来匹配位置块中的代理 url,然后还使用正则表达式作为 proxypass url。当我有一个静态路径时,我的设置当前工作正常,但我想扩展它以使用 2 种或更多类似如下。原文是:

location  /pacs-1/  {

        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_buffering off;
        rewrite /pacs-1/(.*) /$1 break;
        proxy_pass http://pacs-1:8042;
        proxy_redirect  http://pacs-1:8042/ /;

我想做类似以下的事情,这显然不起作用(即(?:pacs-butterfly|pacs-1|pacs-2))。对于代理通行证,我需要使用从位置块匹配的任何路径进行代理重写和代理通行证/重定向。不确定有没有办法做到这一点。

location  /(pacs-butterfly|pacs-1|pacs-2)/ {  #match any of those in ()

. . . not sure how to code what I show below.

        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_buffering off;
        rewrite /(?:pacs-butterfly|pacs-1|pacs-2)/(.*) /$1 break;
        proxy_pass http://(?:pacs-butterfly|pacs-1|pacs-2):8042;
        proxy_redirect  http://(?:pacs-butterfly|pacs-1|pacs-2):8042/ /;

【问题讨论】:

    标签: regex nginx config nginx-reverse-proxy


    【解决方案1】:

    看起来您缺少用于正则表达式匹配的 ~。可以加括号捕获$n格式的变量,$request_uri也可以:

    location ~ ^/(pacs-butterfly|pacs-1|pacs-2)(/.*) {
      default_type text/plain;
      return 200 "
        $1
        $2
        $request_uri
        $args
      ";
    }
    
    $ curl "https://example.com/pacs-1/foo/bar?name=value&foo=bar"
    
        pacs-1
        /foo/bar
        /pacs-1/foo/bar?name=value&foo=bar
        name=value&foo=bar
    

    【讨论】:

    • 我会调查的。我认为我可以使用代理传递和重定向中的变量以及重写?
    • rewrite 指令也可以是独立的,在 location 块之外。
    • 我试过了,它看起来与位置匹配,但重写和传递失败:不确定我会用什么代替 rewrite /pacs-1/(.*) /$1 break; abd 和 proxy_pass pacs-1:8042;。如果我只是用 $1 代替 pacs-1 它是空的,我也尝试使用 set $pacs $1;保存它,但重写仍然不起作用。我基本上想剥离比赛,然后代理传递给 http://{match}:8042
    • 我的原始设置有效。 pacs-1 等是 Docker Container 服务器,因此 http://{match}:8042 向 Container 中的服务器发出请求,否则将被隔离。 auth_request /auth;执行一些授权以允许通过。
    猜你喜欢
    • 2020-09-11
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多