1、location语法规则
location [= | ^~ | ~ | ~* ] /uri/{
# ...
}
location @name {
}
2、location语法详解
规则 | 匹配优先级别 | 正则 | 含义 |
---|
location = /uri | 1 | 否 | = 表示精确匹配,只有完全匹配上才能生效 |
location ^~ /uri | 2 | 否 | ^~ 开头对 URL 路径进行前缀匹配,并且在正则之前 |
location ~ /uri | 3 | 是 | 开头表示区分大小写的正则匹配前 |
location ~* /uri | 4 | 是 | 开头表示不区分大小写的正则匹配 |
location /uri | 5 | 否 | 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后 |
location / | 6 | 否 | 通用匹配,任何未匹配到其它 location 的请求都会匹配到,相当于 switch 中的 default |
注意: 匹配优先级别从小到大,与 location 配置顺序无关
3、location匹配解析
3.1、root解析
解析过程
- location 和 root拼接处理
- 拼接后的 “//” 合并成 “/”
解析示例
location | root | 解析结果 |
---|
/home | html/a/b | html/a/b/home/index.html |
/home/ | html/a/b | html/a/b/home/index.html |
/home | html/a/b/ | html/a/b/home/index.html |
/home/ | html/a/b/ | html/a/b/home/index.html |
3.2、别名alias解析
解析过程
- alias替换访问地址中location匹配的部分
解析示例
location | alias | 解析结果 |
---|
/home | html/a/b | /html/a/b/index.html |
/home/ | html/a/b | /html/a/b/index.html |
/home | html/a/b/ | /html/a/b//index.html |
/home/ | html/a/b/ | /html/a/b/index.html |
3.3、代理proxy_pass解析
解析过程
- 如果代理地址端口后不存在路径,则替换原访问地址location之前的部分
- 如果代理地址端口后存在路径,则(和alias解析一样)替换location匹配部分及之前的部分
解析示例
3.4、@name解析
定义nginx内部服务跳转,可以简单理解为一个location处理function调用。
location / {
root /wwwroot;
try_files index.html index.htm @welcome;
}
# welcome
location @welcome{
root /wwwroot/welcome;
index index.html index.htm;
}