大网数据广告活动
服务器运维问答

Prevent Nginx regex rule to override another rule

· 52CE 我爱测

I have a Nginx server acting as a reverse proxy for a couple services, the config is similar to this one location /backend/service1 { proxy_pass http://pathto/service1; } location / { root /a/folder } location ~* (\.js|\.css)$ ex…

问题原文

原帖链接 · RabidTunes · CC BY-SA 4.0

I have a Nginx server acting as a reverse proxy for a couple services, the config is similar to this one

location /backend/service1 {
        proxy_pass http://pathto/service1;
}

location / {
        root /a/folder
}

location ~* (\.js|\.css)$
        expires 8d;

        root /home/files/abc/bcd;
}

My problem here is that recently the service1 from backend has to serve a couple static files like /backend/service1/something/file1.js or /backend/service1/something/style.css and the second location, since it's a regex location rule, overrides the first one

All static files provided by backend/service1 have a certain prefix (something), so I tried to improve the regex from the second location to have negative lookahead/lookbehind, but it doesn't seem to work, probably because the main pattern has to have a fixed length (this is what i tried without luck)

location /backend/service1 {
        proxy_pass http://pathto/service1;
}

location / {
        root /a/folder
}

location ~* (?<!something)(.*)(\.js|\.css)$
        expires 8d;

        root /home/files/abc/bcd;
}

How can I achieve this?

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

If "something" immediately follows /backend/service1, you can add another more specific location that takes precedence over regex locations:

location /backend/service1 {
    proxy_pass http://pathto/service1;
}  
location ^~ /backend/service1/something/ {
    proxy_pass http://pathto/service1/something/;
}  
location ~* \.(js|css)$ { ... }

If the "something" is embedded anywhere in the URL, you will need to use a regular expression, possibly with the notorious negative lookahead. By trial and error, I found a working expression:

location ~* ^(?!.*something).*\.(js|css)$ { ... }

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-02-02)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。