如何用Nginx反向代理FastAPI后端与React前端及自定义端点
问题背景与需求
- 现有环境:React UI部署在
localhost:5000,FastAPI后端运行在localhost:8000,二者均可正常访问;API文档需通过localhost:8000/docs查看 - 核心需求:
- 访问
localhost时显示React UI - 访问
localhost/api时展示API文档页 - 访问
localhost/api/endpoint时代理到localhost:8000/endpoint - 额外需求:无需
/api前缀,直接通过localhost/endpoint访问后端端点
- 访问
- 当前问题:
/api到/docs的代理失效,/api/endpoint可正常访问但/api/docs无法跳转
修正后的Nginx配置
问题根源在于Nginx的location匹配优先级和路径处理逻辑,以下是调整后的完整配置:
events{ worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; # 根路径优先代理React UI,匹配不到的路径转后端 location / { try_files $uri $uri/ @api_proxy; proxy_pass http://localhost:5000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 精确匹配/api路径,直接跳转到FastAPI文档页 location = /api { proxy_pass http://localhost:8000/docs; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 处理/api/xxx格式的请求,转发到后端对应路径 location /api/ { rewrite ^/api/(.*)$ /$1 break; proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 处理无/api前缀的后端请求(满足额外需求) location @api_proxy { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
配置说明
- 用
location = /api精确匹配路径,避免被/api/的前缀匹配覆盖,确保localhost/api直接跳转到文档页 - 根路径
/中加入try_files规则:优先匹配React的静态资源,匹配不到的请求(如localhost/endpoint)自动转发到后端 - 所有代理块添加
proxy_set_header,确保后端能正确识别请求源,避免FastAPI文档的静态资源加载失败 - 保留
/api/的rewrite规则,保证/api/endpoint能正确映射到后端对应接口
调试路由的方法
方法1:使用echo-nginx-module
如果已安装echo-nginx-module,可以在配置中添加响应头或直接输出代理信息:
location = /api { proxy_pass http://localhost:8000/docs; proxy_set_header Host $host; add_header X-Proxy-Target "http://localhost:8000/docs"; echo "当前代理目标:http://localhost:8000/docs"; }
浏览器开发者工具的响应头会显示X-Proxy-Target,页面也会直接输出代理地址。
方法2:开启Nginx调试日志
在http块中添加详细日志格式,记录每个请求的代理目标:
http { # 其他配置... log_format debug '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$proxy_pass"'; access_log logs/debug.log debug; }
重启Nginx后,logs/debug.log会清晰记录每个请求的实际代理地址。
方法3:添加自定义响应头(无需额外模块)
直接在location块中添加标识头,快速确认匹配的路由:
location / { proxy_pass http://localhost:5000; add_header X-Matched-Location "根路径(React UI)"; }
浏览器响应头会显示当前匹配的location块,便于快速排查路由问题。
内容的提问来源于stack exchange,提问作者Biaspoint
相关产品推荐
相关产品推荐

