Nginx 转发配置
在配置 Nginx 反向代理时,
proxy_pass的路径设置中,是否带有结尾的斜杠 “/” 会直接影响路径的转发方式。以下对绝对路径、相对路径及路径重写的配置进行梳理。
1、proxy_pass
绝对路径:结尾带斜杠
配置示例:
location /proxy {
proxy_pass http://192.168.10.1:8080/;
}
当访问 http://127.0.0.1/proxy/test/test.txt时:
- 匹配到
/proxy路径。 - 将
proxy_pass后面的路径部分/替换/proxy,转发请求为:http://192.168.10.1:8080/test/test.txt。 - 去除匹配路径
/proxy。
相对路径:结尾不带斜杠
配置示例:
location /proxy {
proxy_pass http://192.168.10.1:8080;
}
当访问 http://127.0.0.1/proxy/test/test.txt时:
- 匹配到
/proxy路径。 - 不去除匹配路径
/proxy,将其与proxy_pass后面的地址直接拼接,转发请求为:http://192.168.10.1:8080/proxy/test/test.txt。
代理路径添加 URI
配置示例:
location /proxy {
proxy_pass http://192.168.10.1:8080/static01/;
}
当访问 http://127.0.0.1/proxy/test/test.txt 时:
- 匹配到
/proxy路径。 - 去除
/proxy,并将剩余路径附加到proxy_pass中定义的 URI,转发请求为:http://192.168.10.1:8080/static01/test/test.txt。
2、URL 重写
在某些场景中,需要完全去掉匹配的路径前缀,而不是简单地依赖斜杠规则。
例如,希望访问 http://127.0.0.1/resource/test/test.txt 时代理到 http://192.168.10.1:8082/test/test.txt。
可以使用 rewrite 指令来实现路径的动态重写:
location /resource {
rewrite ^/resource/?(.*)$ /$1 break;
proxy_pass http://192.168.10.1:8082/;
}
解释:
rewrite 的正则匹配与重写:
^/resource/?(.*)$:匹配/resource开头的路径,(.*)表示匹配/resource/后的所有字符。/$1:将捕获的路径部分重写为新的路径,$1引用正则的第一个分组。- 结果:将
/resource/替换为/。
break 指令:
- 指示 Nginx 停止处理后续
rewrite指令链,直接使用重写后的路径进行后续处理。
转发行为:
- 请求
http://127.0.0.1/resource/test/test.txt。 rewrite将路径重写为/test/test.txt。proxy_pass转发到http://192.168.10.1:8082/test/test.txt。

浙公网安备 33010602011771号