一、语法:
location [=|~|~*|^~] /uri/ { … }
二、修饰符:
修饰符 | 类型 | 说明 | 示例 |
---|---|---|---|
= | 普通匹配 | 精确匹配 | location = /url/ |
^~ | 普通匹配 | 普通字符串前缀匹配,忽略后续正则匹配 | location ^~ /url/ |
无 | 普通匹配 | 普通字符串前缀匹配 | location /url/ |
~ | 正则匹配 | 正则匹配,区分大小写 | location ~ .*.(js |
~* | 正则匹配 | 正则匹配,忽略大小写 | location ~* .*.(js |
三、顺序(先查找最长普通匹配,再顺序进行正则匹配):
1、找到精确匹配(=),不再往下查找
2、找到最长普通匹配,没有前缀(^~),往下顺序查找正则匹配
(1)找到符合的正则匹配,不再查找
(2)没有符合的正则匹配,使用最长普通匹配
3、找到最长普通匹配,有前缀(^~),不再往下查找
4、顺序查找正则匹配
四、示例
在线测试:https://nginx.viraptor.info/
1、
server {
listen 80;
server_name test.com www.test.com;
# A
location ^~ /static/ {}
# B
location /static/js {}
# C
location ~* /(static|public)/ {}
# D
location = / {}
}
http://test.com/ -> D http://test.com/static -> A http://test.com/static/js -> C 这里B永远匹配不上,因为能匹配B的情况下,也都能匹配C
2、
server {
listen 80;
server_name test.com www.test.com;
# A
location = / { }
# B
location / { }
# C
location /user/ { }
# D
location ^~ /images/ { }
# E
location ~* \.(gif|jpg|jpeg)$ { }
}
http://test.com/index.html -> B http://test.com/documents/about.html -> B http://test.com/user/index.html -> C http://test.com/user/abc.jpg -> E http://test.com/images/abc.jpg -> D http://test.com/ -> A
No comments:
Post a Comment