Nginx反向代理配置引发404 Not Found问题求助
Nginx反向代理配置引发404 Not Found问题求助
问题分析
你的核心问题出在单个location /块同时处理前端路由和后端API代理,导致请求逻辑冲突:
- 当所有请求都通过
proxy_pass转发到Spring服务时,React的单页应用路由(比如/dashboard这类前端路径)会被发送到Spring,但Spring没有对应的接口,直接返回404; - 而如果去掉代理配置,前端页面能正常加载,但API请求找不到后端服务,自然也会失败。
解决方案
你需要把前端页面请求和后端API请求分开配置,让Nginx根据请求路径区分处理:
修改后的Nginx配置示例
server { listen 443 ssl; server_name 193.xxx.xx.xxx; ssl_certificate nginx.crt; ssl_certificate_key nginx.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4; ssl_prefer_server_ciphers on; root /var/www/193.xxx.xx.xx; index index.html; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # 1. 处理后端API请求(假设你的API前缀是/api,根据实际情况调整) location /api/ { proxy_pass https://193.xxx.xx.xx:8443/api/; proxy_ssl_verify off; 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_connect_timeout 1; proxy_next_upstream error timeout http_500 http_502 http_503 http_504 http_404; proxy_intercept_errors on; allow all; } # 2. 处理前端单页应用路由和静态资源 location / { try_files $uri $uri/ /index.html; # 确保React路由能正确返回index.html error_page 405 =200 $uri; allow all; } location ~ /.well-known { allow all; } }
关键说明
- 路径区分:通过
/api/前缀把API请求单独代理到Spring服务,前端页面和静态资源请求由Nginx直接处理; - proxy_pass路径匹配:注意
location /api/和proxy_pass末尾的斜杠,确保路径拼接正确(比如请求/api/user会转发到https://193.xxx.xx.xx:8443/api/user); - React路由兼容:
try_files $uri $uri/ /index.html是单页应用的标准配置,能让Nginx在找不到对应静态文件时返回index.html,保证React路由正常工作; - 自定义API前缀:如果你的后端API不是
/api开头,记得修改location和proxy_pass的路径,比如改成/service/或者其他你实际使用的前缀。
测试步骤
- 重启Nginx服务:执行
sudo nginx -s reload,确保配置生效; - 测试前端页面:访问你的域名/IP,检查页面是否能正常加载和跳转;
- 测试API请求:用curl或者Postman调用API接口(比如
https://193.xxx.xx.xxx/api/xxx),确认能正常返回后端数据。
备注:内容来源于stack exchange,提问作者Beesz




