【问题标题】:NGinx location directive with Regex带有正则表达式的 NGinx 位置指令
【发布时间】:2021-03-19 10:53:37
【问题描述】:

我正在寻找一种方法让我的 NGinx LB 进行以下转换。

  • 用户访问地址:https://example.com/t/foo.com/common/<something>
  • 由 LB 代理:https://example.com/<something>?t=foo.com

首先,这可以做到吗?

我尝试了以下配置,但没有按预期工作。

server {
    listen 443;
    server_name example.com;
    ssl on;
    ssl_certificate /etc/ssl/certs/example-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/example-selfsigned.key;
    
    location /t/[a-z.]+/common/ {

        rewrite ^(/t/.*)/common/(.*)$ https://192.168.1.3:9443/$2?t=$1 break;

        proxy_pass https://192.168.1.3:9443/;

    }
}

对此的任何帮助将不胜感激!

【问题讨论】:

    标签: regex nginx redirect proxy load-balancing


    【解决方案1】:

    正则表达式匹配位置应使用~(或~* 用于不区分大小写的匹配)修饰符。当您想重写要使用 proxy_pass 指令代理的 URI 时,不应将方案或域部分添加到您的 rewrite 指令中。请尝试以下操作:

    location ~ ^/t/(?<t>[a-z.]+)/common(?<path>/.*) {
        rewrite ^ $path?t=$t break;
        proxy_pass proxy_pass https://192.168.1.3:9443;
    }
    

    【讨论】:

    • 非常感谢@Ivan 的回答。但我遇到了一个错误。 nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /etc/nginx/conf.d/example.conf:12
    • 抱歉,我忘记在rewrite 指令上指定break 标志,已修复该问题。您应该完全使用proxy_pass proxy_pass https://192.168.1.3:9443;,如答案中所示没有尾随斜杠。
    猜你喜欢
    • 2020-09-11
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多