bash
http {
server {
listen 80;
server_name www.xxx.com;
location / {
root /share/nginx/html/;
index index.html;
}
}
}
一、语法
=
表示精确匹配bashlocation = /test { [configration] } # /test ok # /test/ not ok # /test1/ not ok # /test/1 not ok
~
表示区分大小写的正则匹配bashlocation ~ ^/test$ { [configration] } # /test ok # /Test/ not ok # /test/ not ok # /test1 not ok
~*
不区分大小写的正则匹配bashlocation ~* ^/test$ { [configration] } # /test ok # /Test ok # /test/ not ok # /test1 not ok
^~
表示uri以某个字符串开头bashlocation ^~ /test/ { [configration] } # /test ok # /test/1.html ok # /tes/ not ok
当不使用这些语法时,只写uri的时候,/
表示通用匹配
bash
location /test {
[configration]
}
# /test ok
# /test/1.html ok
# /test1/ ok
二、匹配顺序
location
的定义分为两种,前缀字符串(prefix string)和正则表达式(regular expression)
- 检查使用前缀字符串的 locations,在使用前缀字符串的 locations 中选择最长匹配的,并将结果进行储存
- 如果符合带有
=
修饰符的 URI,则立刻停止匹配 - 如果符合带有
^~
修饰符的 URI,则也立刻停止匹配。 - 然后按照定义文件的顺序,检查正则表达式,匹配到就停止
- 当正则表达式匹配不到的时候,使用之前储存的前缀字符串
- 在顺序上,前缀字符串顺序不重要,按照匹配长度来确定,正则表达式则按照定义顺序。
- 在优先级上,
=
修饰符最高,^~
次之,再者是正则,最后是前缀字符串匹配
三、root和alias
root
使用的是拼接root+location
,alias
是用alias
替换location
,
bash
location /test/ {
root /rootdir/
}
# 当请求 /test/1.html的时候,/rootdir/test/1.html会返回
location /test1/{
alias /aliasdir/
}
# 当请求 /test1/2.html的时候,/rootdir/1.html会返回
==root可能更好用==