location配置
语法规则
location [=|~|~*|^~] /uri/ {… }
在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;nginx会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配
= | 表示精确匹配 |
---|---|
~ | 表示对URI做区分字符大小写的正则匹配 |
~* | 表示对URI做不区分字符大小写的正则匹配 |
^~ | 对URI的最左边部分做匹配检查,不区分字符大小写 |
- 匹配优先级由高到低:=,^,/~*,不带符号的
location匹配示例
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /dh/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
# \. 是转义的 .
# $ 表示以(gif|jpg|jpeg|png)结尾
location ~* \.(gif|jpg|jpeg|png)$ {
[ configuration E ]
}
-
/
请求将匹配配置A -
/index.html
请求将匹配配置B -
/dh/adrian.html
请求将匹配配置C -
/images/1.gif
请求将匹配配置D^~ 以左边 /images/ 做匹配检查,后面跟什么内容都可以
^~的优先级比 ~* 的优先级高,所以会先匹配D
-
/dh/1.jpg
请求将匹配配置E
-
location中使用root和alias的区别
- root:设置web资源的路径映射,指明请求URL所对应的文档的目录路径,可用于http,server,location
- alias:路径别名,仅能用于location上下文
location /dh/ { alias /web/data; } location /dh { root /web/data; } # 如果访问 http://www.dh.com/dh/index.html ## 如果是alias配置,那么会转到 /web/data/index.html ## 如果是root配置,那么转到 /web/data/dh/index.html