如何解决Nginx 位置正则表达式父、子和代理
需要帮助为我的 nginx 代理编写正确的 location
正则表达式。
location /
正在代理外部网站
但是有几个路径被代理到具有以下目录树的本地静态站点:
├── index.html
└── parent
├── child-1
│ └── index.html
├── child-2
│ └── index.html
└── index.html
我需要/parent/
服务于 parent/index.html
/parent/child-1/
服务于 parent/child-1/index.html
/parent/child-2/
服务于 parent/child-2/index.html
不过/parent/other-children
被代理到 location /
这是我尝试过的:
location / {
proxy_pass https://xyz$request_uri;
}
location ~ ^/parent/$ {
index index.html index.htm;
root /var/www/sites/dist;
}
location ~ ^/parent/(child-1|child-2) {
index index.html index.htm;
root /var/www/sites/dist;
}
有了这个设置
/parent/
有效/parent/child-1
有效/parent/child-2
有效
/parent/other-children
显示 404 Not Found
如果有人可以帮助我通过 location /
使 /parent/other-children 代理到外部服务器
提前致谢。
解决方法
想通了。
要达到预期的结果,应使用 try_files
指令。
这是工作示例:
location / {
proxy_pass https://xyz$request_uri;
}
location /parent/ {
root /var/www/sites/dist;
index index.html index.htm
try_files $uri $uri/ /;
}
try_uri
- 首先查找与请求 URI
($uri)
匹配的文件是否存在 - 如果未找到,则检查是否存在同名目录
($uri/)
- 如果没有找到,则代理到
location /
要使 try_uri
工作,需要指定 root
文件夹,它将在其中搜索文件/目录。如果找到目录,它还需要知道要提供的默认文件。为此,应指定 index
指令,其中包含要按优先级顺序提供的默认文件列表。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。