NGINX 正则表达式位置 - 以 X 开头且不包含 Y

NGINX Regex location - Starts with X AND does not contain Y

我有以下位置配置:

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

/cars

等,我希望他们通过基本身份验证进行身份验证。但是当有人向

提出请求时

/trucks?id=123

/cars?id=124

那么我不需要身份验证,处理较低的位置块。

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

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

尝试以下正则表达式:

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

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

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

DEMO.