Nginx 转发配置

原文:Nginx 中 proxy_pass 的路径解析详解

在配置 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时:

  1. 匹配到 /proxy 路径。
  2. proxy_pass 后面的路径部分 / 替换 /proxy,转发请求为:http://192.168.10.1:8080/test/test.txt
  3. 去除匹配路径 /proxy

相对路径:结尾不带斜杠

配置示例:

location /proxy {
    proxy_pass http://192.168.10.1:8080;
}

当访问 http://127.0.0.1/proxy/test/test.txt时:

  1. 匹配到 /proxy 路径。
  2. 不去除匹配路径 /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 时:

  1. 匹配到 /proxy 路径。
  2. 去除 /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 指令链,直接使用重写后的路径进行后续处理。

转发行为:

  1. 请求 http://127.0.0.1/resource/test/test.txt
  2. rewrite 将路径重写为 /test/test.txt
  3. proxy_pass 转发到 http://192.168.10.1:8082/test/test.txt
posted @ 2025-09-09 15:29  ioufev  阅读(152)  评论(0)    收藏  举报