Nginx多个location匹配

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nginx多个location匹配相关的知识,希望对你有一定的参考价值。

多个 location 配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):

首先匹配 =
其次匹配 ^~
其次是按文件中顺序的正则匹配
最后是交给 / 通用匹配
当有匹配成功时候,停止匹配,按当前匹配规则处理请求

例子,有如下匹配规则:

location = / {
#规则A
}
location = /login {
#规则B
}
location ^~ /static/ {
#规则C
}
location ~ .(gif|jpg|png|js|css)$ {
#规则D
}
location ~* .png$ {
#规则E
}
location / {
#规则F
}

那么产生的效果如下:

访问根目录 /, 比如 http://localhost/ 将匹配规则 A
访问 http://localhost/login 将匹配规则 B,http://localhost/register 则匹配规则 F
访问 http://localhost/static/a.html 将匹配规则 C
访问 http://localhost/a.gif, http://localhost/b.jpg 将匹配规则 D 和规则 E,但是规则 D 顺序优先,规则 E 不起作用,而 http://localhost/static/c.png 则优先匹配到规则 C
访问 http://localhost/a.PNG 则匹配规则 E,而不会匹配规则 D,因为规则 E 不区分大小写。

访问 http://localhost/category/id/1111 则最终匹配到规则 F,因为以上规则都不匹配

以上是关于Nginx多个location匹配的主要内容,如果未能解决你的问题,请参考以下文章

Nginx Location匹配顺序

nginx location正则匹配同路径下多个文件?

详细解析 nginx uri 如何匹配 location 规则

[nginx]location语法

nginx——location匹配流程图

Nginx正则匹配详解