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

Nested Nginx location (prefix blocks in regex blocks) not working

· 52CE 我爱测

I'm having trouble understanding nested locations in nginx. I have two locations with some configuration directives in common, so rather than repeat the directives, I'd prefer to repeat the URI using a regular-expression: locatio…

问题原文

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

I'm having trouble understanding nested locations in nginx. I have two locations with some configuration directives in common, so rather than repeat the directives, I'd prefer to repeat the URI using a regular-expression:

location ~ /a|/b {
        location /a {
        }
        location /b {
        }
}

However, this gives the error

nginx: [emerg] location "/a" is outside location "/a|/b" in /etc/nginx/nginx.conf:36

Without the or | it seems okay, though.

location ~ /a {
        location /a {
        }
}

What am I doing wrong? Is there a better way to do this without repeating anything? Can I group locations in another way?

已采纳解答

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

Old question, but the issue is because the parent location is a regex location while the nested locations are prefix locations.

When a parent location is defined by a regex, any nested locations must also be defined by regexes:

location ~ ^/(a|b) {
        location ~ ^/a {
        ...
        }
        location ~ ^/b {
        ...
        }
}

You may only define nested prefix locations when the parent location is also a prefix location:

location /a {
        location /a {
               # You can also skip this location and just write
               # your code directly under the parent location
        }
        location /a/b {
        ...
        }
}

However, you may define nested regex locations when the parent location is a prefix location:

location /a/b {
        location ~ /a {
        ...
        }
        location ~ /b {
        ...
        }
}

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

资料来源与适用范围

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

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

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