关于路径匹配
问题:访问 uri 时,出现 404 问题
uri:http://localhost/app
nginx 配置如下
location /app {
root /var/www/html;
}
1
2
3
2
3
在 /var/www/html 存在 index.html,为什么访问会得到 404 呢?其实 location 不仅要对 uri 进行匹配,也要对本地的文件资源进行匹配,匹配的是 /var/www/html/app 文件
所以很显然,下列列表中的 uri 匹配的都是 app 文件夹下的 index.html,而不是通过 /app 去访问根目录下的 index.html
- http://localhost/app/
- http://localhost/app/index.html
通过 curl -i http://localhost/app/ 可以正常得到 /var/www/html/app/index.html 这个文件
问题:使用 nginx ~* 忽略大小写匹配时,访问资源失败 404
目标资源访问 uri:http://localhost/videos/Video9.avi
目标资源:/videos/video9.avi
虽然 ~* 是用来忽略大小写进行匹配的,但是用户访问还是要与实际文件路径一致,这会受到操作系统等因素的影响
问题:重写路径后,转发的路径不是预期路径
nginx 配置:
location /api/ {
proxy_pass http://backend;
}
1
2
3
2
3
请求 uri:/api/test,重写后路径:http://backend/api/test
但是如果 proxy_pass http://backend/,重写路径后:http://backend/test (opens new window)
这个行为的原因在于 nginx 的 proxy_pass 指令在处理路径时的规则
- 当 proxy_pass 后的地址不包含尾部的斜杠 / 时,nginx 会将 location 块中匹配到的路径部分保留并追加到后端地址,适用于后端服务需要完整路径的情况,例如 API 网关
- 当 proxy_pass 后的地址包含尾部的斜杠 / 时,nginx 会将 location 块中匹配到的路径部分去掉,仅保留剩余的 URI 部分,直接拼接到后端地址,适用于后端服务不需要前缀或希望简化路径的情况