反向代理配置示例
转发 HTTP 请求并理解路径替换规则
配置骨架(非 Shell 命令)
location /api/ {
proxy_pass http://127.0.0.1:3000;
}说明
适用于前端站点转发后端 API。以下 location 片段放入站点配置(如 /etc/nginx/conf.d/site.conf)的目标 server 块,示例上游为 127.0.0.1:3000,需替换为真实应用地址。proxy_pass 是否带 URI 会影响路径替换;配置修改后先检查通过再重载,并通过请求验证实际路径。
示例
保留 /api/ 前缀
请求 /api/users 转发后仍是 /api/users。
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}注意事项:上游只能信任可信代理提供的转发头;不能无条件信任客户端提交的 X-Forwarded-For。
移除 /api/ 前缀
proxy_pass 带尾部斜杠 URI,请求 /api/users 转发为 /users。
location /api/ {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}注意事项:此路径替换示例针对普通前缀 location;正则 location、变量 URL 和 rewrite 场景不能直接套用。读取超时是两次读取间的超时,不是整个请求总时限。