ReactJS+NGINX配置:如何在NGINX上同时运行SPA与代理路由?
解决MERN栈部署后前端路由手动输入/刷新失效问题
你的问题核心是React单页应用(SPA)的前端路由需要NGINX配合,把非后端API的请求都转发到index.html,由React Router处理。修改NGINX配置如下:
location / { root /root/amfmfx.com/build; index index.html; # 先尝试匹配静态文件,再匹配目录,最后返回index.html交由前端路由处理 try_files $uri $uri/ /index.html; } location /user { proxy_pass http://loadbalancer; proxy_buffering on; } location /api { proxy_pass http://loadbalancer; proxy_buffering on; } location /email { proxy_pass http://loadbalancer; proxy_buffering on; }
关键修改说明
- 把原配置里的
try_files $uri $uri/ =404;改成try_files $uri $uri/ /index.html;:- 当请求是静态资源(如
static/js/main.xxx.js、static/css/main.xxx.css),$uri会匹配到对应的文件,正常返回资源; - 如果请求是目录(比如不存在的
/assets/),$uri/尝试访问目录,若不存在则跳转到index.html; - 所有前端路由(如
/login、/dashboard)这类不存在对应文件的请求,都会返回index.html,由React Router解析并渲染对应页面。
- 当请求是静态资源(如
额外注意事项
- 确保
/root/amfmfx.com/build目录的权限正确,NGINX进程需要有读取该目录及文件的权限; - 修改配置后,执行
sudo nginx -t检查配置语法是否正确,再执行sudo systemctl reload nginx生效配置。
内容的提问来源于stack exchange,提问作者troy
相关产品推荐
相关产品推荐

