1、location语法规则
location [= | ^~ | ~ | ~* ] /uri/{
# ...
}
// 定义nginx内部服务跳转
location @name {
}
//JS中文网 – 前端进阶资源分享 https://www.javascriptc.com/ 趣聊CSS系列
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匹配解析
- 测试访问: http://localhost/home/index.html
- nginx html目录结构:/a/b/home/index.html
- 代理nginx:http://localhost:8080
- 代理nginx html目录 /index.html、/proxy_home/index.html
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匹配部分及之前的部分
解析示例
location
proxy_pass
解析结果
/home
http://localhost:8080
/home/index.html
/home/
http://localhost:8080
/home/index.html
/home
http://localhost:8080/
//index.html
/home/
http://localhost:8080/
/index.html
/home
http://localhost:8080/proxy_home
/proxy_home/index.html
/home/
http://localhost:8080/proxy_home
/proxy_homeindex.html
/home
http://localhost:8080/proxy_home/
/proxy_home//index.html
/home/
http://localhost:8080/proxy_home/
/proxy_home/index.html
3.4、@name解析
定义nginx内部服务跳转,可以简单理解为一个location处理function调用。
nginx
location / {
root /wwwroot;
try_files index.html index.htm @welcome;
}
# welcome
location @welcome{
root /wwwroot/welcome;
index index.html index.htm;
}
//JS中文网 – 前端进阶资源分享 https://www.javascriptc.com/ 趣聊CSS系列
作者:__此间少年
链接:https://juejin.im/post/6877012872120303630
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程