location语法
location语法格式
location [=|~|~*|^~] uri {
....
}
location [=|~|~*|^~] uri {....}
指令 匹配标识 匹配的网站地址 匹配URI后要执行的配置段
~ 与~* 的区别
location字段 | 说明 |
---|---|
~ | 匹配内容区分大小写 |
~* | 匹配内容不区分的小写 |
!~ | 取反 |
^~ | 但多个匹配同时存在,优先匹配 ^~匹配的内容;不做正则表达式的检查 (优先处理) |
location官方示例
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
- 说明
"/" 请求将匹配配置A,
"/index.html" 请求将匹配配置B,
"/documents/document.html" 请求将匹配配置C,
"/images/1.gif" 请求将匹配配置D,
"/documents/1.jpg" 请求将匹配配置E.
按匹配顺序
location = / { # 精确匹配 /
[ configuration A ]
}
location ^~ /images/ { # 匹配常规字符串,不做正则表达式匹配检查
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ { # 正则匹配
[ configuration E ]
}
location /documents/ { # 匹配常规字符串,如果有正则,则优先匹配正则
[ configuration C ]
}
location / { # 所有location 都不能匹配后的默认匹配
[ configuration B ]
}
- 不同uri及特殊字符组合匹配的顺序说明
测试location的访问
修改返回值
server {
listen 80;
server_name www.maotai.com maotai.com;
root html;
location / {
return 401;
}
location = / {
return 402;
}
location /documents/ {
return 403;
}
location ^~ /images/ {
return 404;
}
location ~* \.(gif|jpg|jpeg)$ {
return 500;
}
access_log logs/access_www.log main;
}
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/documents
401
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com
402
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/documents/
403
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/images/1.jpg
404
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/documents/ss.jpg
500