Linux_260_Nginx之Location匹配机制
nginx的location作用是根据用户访问的url,进行不同的处理方式。针对用户请求的网站URL进行匹配处理,然后进行对应的处理
location在nginx.conf写法
location / {
# root关键词是定义网页根目录的,这个html是以nginx安装的路径为相对
root /web/yu;
# index关键词,定义nginx的首页文件名字,默认找哪个文件
index index.html index.htm
}
location相关语法
location [ = | ~ | ~* | ^* ] url {
# 做出的相应的处理动作
}
| 表示或者
nginx有关location的匹配,符合如下
匹配符 匹配规则 优先级
= 精确匹配 1
^~ 以某个字符开头,不做正则处理 2
~* 支持正则的匹配模式 3
/blog/ 当你访问192.168.178.120/blog/xxxx,访问这个文件夹下的内容 4
/ 通用匹配,不符合其他的location的匹配规则就走到这里 5
表示nginx.conf支持在虚拟主机中定义多个location,进行用户的请求url解析
nginx的location实战演练如下
准备一个nginx的配置文件,来练习location语法
vim my_location.conf
使用 IP:端口 进入如下的虚拟主机
server {
listen 83;
server_name _;
# 最低级匹配,不符合其他locaiton就来这
# 比如当用户访问 192.168.178.129:83/hehe,nginx直接返回401状态码给用户
location / {
return 401;
}
# 优先级最高,精确匹配,当用户访问 192.168.178.110:83/
location = / {
return 402;
}
# 当用户访问192.168.178.110/blog/hehe.txt
# 以/blog/开头的url,来这里,如符合其他locaiton,则以其他优先
location /blog/ {
return 403;
}
# 当用户访问 192.168.178.110/img/xxx
# 匹配任何以/img/开头的请求,不匹配正则
location ^~ /img/ {
return 404;
}
# 支持正则匹配的url
# 当用户访问任意url,结尾是以.gif,.jpg,.jpeg的时候,就进入如下location
# 匹配任何以.gif结尾的请求,支持正则
location ~* .(gif|jpg|jpeg)$ {
return 500;
}
}
server {
listen 83;
server_name _;
location / {
return 401;
}
location = / {
return 402;
}
location /blog/ {
return 403;
}
location ^~ /img/ {
return 404;
}
location ~* .(gif|jpg|jpeg)$ {
return 500;
}
}
访问结果(注意优先级)
http://192.168.178.120:83/ 402 Payment Required
http://192.168.178.120:83/1 401 Authorization Required
http://192.168.178.120:83/blog/ 403 Forbidden
http://192.168.178.120:83/img/ 404 Not Found
http://192.168.178.120:83/blog/xxx/xxx.jpg 500 Internal Server Error