nginx的官方文档location支持以下几种形式的配置,
location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
我们一般也就用三种配置,= 精确匹配,[^~]/ 前缀匹配,~或~* 正则匹配。 这个顺序也是他们匹配的顺序,前缀匹配会最大限度的匹配,例如 /test/ 和 /test/hello 如果你的url是/test/helloworld 会匹配到location /test/hello。
这个匹配规则和你在配置文件中配置的location的先后顺序没有关系,不会因为location /test/ {} 在 location /test/hello {}就让url /test/helloworld 先匹配第一个location。
利用我github ngx_http_hello_world_module 模块测试一下。从github上clone下来以后,编译的时候在configure添加–add-module=./vislee/ngx_http_hello_world_module后编译。
测试配置文件:
location ^~/test0/ {
hello_world;
hello_by "by ^~/test0/";
location ^~/test0/hello/ {
hello_world;
hello_by "by nested ^~/test0/hello";
}
location ^~/test0/world/ {
hello_world;
hello_by "by nested ^~/test0/world/";
}
}
location ^~/test0/hello/ {
hello_world;
hello_by "by ^~/test0/hello";
}
location =/test0/ {
hello_world;
hello_by "by =/test0/";
}
location ^~/test {
hello_world;
hello_by "by ^~/test";
}
location ^~/test/ {
hello_world;
hello_by "by ^~/test/";
}
location ^~/testa {
hello_world;
hello_by "by ^~/testa";
}
测试结果:
curl -v 'http://127.0.0.1:8080/test0/ hello world by =/test0/% curl -v 'http://127.0.0.1:8080/test0/test' hello world by ^~/test0/% curl -v 'http://127.0.0.1:8080/test0/hello/' hello world by ^~/test0/hello% curl -v 'http://127.0.0.1:8080/test0/world/' hello world by nested ^~/test0/world/%
总结:
先匹配精确匹配的location,也就是配置location = xxx {}的。
其次匹配前缀匹配的location,也就是配置location [^~] xxx {}的。先匹配前缀较长的,相同长度的先匹配字典顺序较大的。
最后匹配正则表达式的location,也就是配置location ~ xxx {}的。

FROM:https://github.com/vislee/
转载请注明:爱开源 » nginx location 的匹配顺序