从零开始学习Linux:Day09 Nginx之location
location 是用来快速进行资源定位,可以定义不同的方式来处理或解决url请求。
来看下面例子:
- localtion / 匹配
# "/" 是直接到nginx发布目录/usr/local/nginx/html/里来查资源,比如location.html location / { root html; index index.html index.htm; }
在发布目录里创建location.html文件,内容为:this is location.html。执行192.168.68.128/location.html时,服务器会到“/”根目录( 192.168.68.128/ )里找这个location.html文件,并把结果this is loction.html返回出来,测试结果:
2、location = / 精准匹配
现在修改nginx配置文件,
增加一个location来直接定位到location.html
location = /localtion.html {
root /data/;
index index.html index.htm;
}
重启服务,测试:
1、先不在/data/目录创建location.html。可以看到,服务器去第二个location里寻找location.html这个文件,而不是去第一个location里找。由于第二个location指定的目录是/data/,/data/目录下没有location.html文件,报404错误。:
2、在/data/下创建location.html文件。
echo "this is other location.com" > /data/location.html
再次访问192.168.68.128/location.html,找到了location.html,但并不是到/根去找,而是到/data/目录里去找。可见:location /的优先级,比精准匹配 location = /要低。精准匹配不论是在配置文件内容上面还是下面,服务器首先去找精准匹配的内容。
除以精准匹配,还有~ ~ ^~
~是对大小写敏感,匹配时严格大小写
~ 是对大小写不敏感,匹配进不分大小写。
^~用来匹配以uri开头,匹配成功以后,会停止搜索后面的正则表达式匹配。
以上优先最高的是精准匹配。location = /
其次是:^~
然后是~ ,~* 这两种看准在配置文件内容上面,就先匹配谁。
优先级最低的是根,/