Nginx的location匹配优先级
1、location的语法规则
location [=|^~|~|~*] /url/ …
符号 | 含义 |
---|---|
= | 表示精确匹配,输入的url名必须相同 |
^~ | 表示匹配以某个字符串开头的url路径 |
~ | 表示匹配区分大小写的url字符正则表达式 |
~* | 表示匹配不区分字符串大小写的url正则表达式 |
/filename | 表示匹配此url路径下的的文件资源 |
/ | 通用匹配,任何的请求都会被匹配到 |
2、location匹配的优先级
(=) >(^~) > (~) >(~*) > (/filename) >(/)
3、匹配案例演示:
location = /aaa/ {
root /nginx/web/;
index index.html; //这是精确匹配,只能是输入/aaa/才会被匹配到的资源;
}
location ^~ /bbb/ {
root /nginx/web;
index index.html; //这是以/bbb/资源开头的资源,访问的路径为/nginx/web/bbb/index.html;
}
location ~ \.(jpg|gif|png)$ {
root /nginx/web/image; //这是区分大小写的图片资源路径;
}
location ~* \.jpg$ {
root /nginx/web; //这是不区分字符大小写的图片资源路径;
}
location /nginx/web {
root /nginx/web/; //这是指定目录路径匹配,访问/nginx/web资源都是访问该目录下的index.html资源;
index index.html;
}
location / {
root /nginx/web; //这是通用匹配,会访问/nginx/web/index2.html资源文件;
index index2.html;
}
首先我们做精确资源路径匹配,查看是否能访问到aaa目录的资源文件(注意:字符串一定要一样)
再尝试对bbb目录的访问:
然后对图片做访问,我输出的是大写的字符路径,所以直接匹配到了/nginx/web/image目录里面的资源
然后做指明路径的访问和不指明路径的资源访问
然后不指明资源位置路径,看看是否会访问到/nginx/web/index2.html