【问题标题】:NGINX Regex location - Starts with X AND does not contain YNGINX 正则表达式位置 - 以 X 开头并且不包含 Y
【发布时间】:2016-06-27 10:58:26
【问题描述】:

我有以下位置配置:

location ~ ^/(trucks|cars|planes|system|tools) {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/htauth_file;
        proxy_set_header Host "server.lan";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass  http://127.0.0.1:8080$request_uri;
}

任何人

提出请求时

/卡车

/汽车

等,我希望它们通过基本身份验证。但是当有人提出要求时

/trucks?id=123

/cars?id=124

然后我不想要身份验证,处理较低的位置块。

当URI中有问号时,我基本上不希望位置匹配。

有没有办法修改我粘贴的配置,使其在 URI 中有问号时不匹配?

【问题讨论】:

    标签: regex nginx configuration


    【解决方案1】:

    我建议使用以下正则表达式:

    ^/(trucks|cars|planes|system|tools)(?![^\s?]*\?)
    

    DEMO.

    【讨论】:

    • 这很完美!并感谢您提供演示链接。
    【解决方案2】:

    尝试以下正则表达式:

    location ~ ^/[^?]+ {
            auth_basic "Restricted";
            auth_basic_user_file /etc/nginx/htauth_file;
            proxy_set_header Host "server.lan";
            proxy_set_header X-Real-IP $remote_addr;
            proxy_pass  http://127.0.0.1:8080$request_uri;
    }
    

    它会:

     /cars <--match
     /trucks <--match
     /trucks?id=123 <-- no match
    

    【讨论】:

    • 感谢您的回复!我有几个位置块,最后一个有location /。我尝试使用这个:location ~ ^/(trucks|cars)[^?]+,但它对我不起作用。还有其他方法可以修改它以使其正常工作吗?
    • 在匹配位置时忽略参数,但可以在位置块内使用条件表达式,例如 if ($args ...)
    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多