Nginx location(正则)
- 1、nginx location
- 2、匹配标识说明
- 3、不同uri及特殊字符组合匹配的顺序说明
- 4、示例
1、nginx location
location 指令的作用是根据用户请求的URI来执行不同的应用。
location使用的语法为:
location [=|~|~*|^~] uri {
······
}
解释
location | [=||*|^~] | uri | {…} |
---|---|---|---|
指令 | 匹配标识 | 匹配的网站地址 | 匹配URI后要执行的配置段 |
2、匹配标识说明
1.~ 匹配内容区分大小写
2.~* 匹配内容不区分的小写
3.!~ 取反
4.^~ 但多个匹配同时存在,优先匹配 ^~匹配的内容;不做正则表达式的检查 (优先处理)
3、不同uri及特殊字符组合匹配的顺序说明
顺序 | 不用URI及特殊字符组合匹配 | 匹配说明 |
---|---|---|
1 | location = / {} | 精确匹配 / |
2 | location ^~ /image/{ | 匹配常规字符串,不做正则表达式匹配检查 |
3 | location ~* \.(gif|jpg|jpeg)$ {
|
正则匹配 |
4 | location /documents/ { | 匹配常规字符串,如果有正则,则优先匹配正则 |
5 | location / { | 所有location 都不能匹配后的默认匹配 |
4、示例
测试代码
#location / {
# root html;
# autoindex on;
# index index.html index.htm;
#}
location / {
return 401;
}
location = / {
return 402;
}
location /documents/ {
return 403;
}
location ^~ /images/ {
return 404;
}
location ~* \.(gif|jpg|jpeg)$ {
return 500;
}
访问测试
[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12/docuements
401
[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12
402
[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s http://192.168.150.12/documents/
403
[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12/images/a.jpg
404
[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12/docuements/abc.jpg
500