本文主要探讨一下使用Nginx进行反代时,location中的location以及proxy_pass带斜杠的分析。
四种情况
location结尾不带斜杠,proxy_pass结尾不带斜杠
location /test-locaion-and-p {
proxy_pass http://127.0.0.1:5000;
}
请求/test-locaion-and-p被转发到http://127.0.0.1:5000/test-locaion-and-p
请求/test-locaion-and-p/sub被转发到http://127.0.0.1:5000/test-locaion-and-p/sub
location结尾带斜杠,proxy_pass结尾不带斜杠
location /test-p/ {
proxy_pass http://127.0.0.1:5000;
}
请求/test-p/被转发到http://127.0.0.1:5000/test-p/
请求/test-p/sub被转发到http://127.0.0.1:5000/test-p/sub
location结尾不带斜杠,proxy_pass结尾带斜杠
location /test-location {
proxy_pass http://127.0.0.1:5000/;
}
请求/test-location被转发到http://127.0.0.1:5000/
请求/test-location/sub被转发到http://127.0.0.1:5000//sub
location结尾带斜杠,proxy_pass结尾带斜杠
location /test/ {
proxy_pass http://127.0.0.1:5000/;
}
请求/test被转发到http://127.0.0.1:5000/
请求/test/sub被转发到http://127.0.0.1:5000/sub
总结
由以上的结果能够看到
location后是否带斜杠影响不大,而proxy_pass的url后面是否带/将影响反代到的实际路径。
- 当proxy_pass的url不带
/时,最终的请求路径就是proxy_pass的路径+实际的请求路径。- 如果 proxy_pass 不包含 URI(例如 proxy_pass http://127.0.0.1:8080;),匹配到的 location 路径会直接追加到 proxy_pass 后面。
请求 /api/test 会转发到 http://127.0.0.1:8080/api/test。
- 如果 proxy_pass 包含 URI(例如 proxy_pass http://127.0.0.1:8080/api;),匹配到的 location 路径会被 proxy_pass 中的 URI 替换。
请求 /api/test 会转发到 http://127.0.0.1:8080/api/test。
- 如果 proxy_pass 不包含 URI(例如 proxy_pass http://127.0.0.1:8080;),匹配到的 location 路径会直接追加到 proxy_pass 后面。
- 当proxy_pass的url带
/,最终的请求路径为proxy_pass的路径+实际路径去除location的部分。