You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;:
    1. 当请求是静态资源(如static/js/main.xxx.js、static/css/main.xxx.css),$uri会匹配到对应的文件,正常返回资源;
    2. 如果请求是目录(比如不存在的/assets/),$uri/尝试访问目录,若不存在则跳转到index.html;
    3. 所有前端路由(如/login、/dashboard)这类不存在对应文件的请求,都会返回index.html,由React Router解析并渲染对应页面。

额外注意事项

  • 确保/root/amfmfx.com/build目录的权限正确,NGINX进程需要有读取该目录及文件的权限;
  • 修改配置后,执行sudo nginx -t检查配置语法是否正确,再执行sudo systemctl reload nginx生效配置。

内容的提问来源于stack exchange,提问作者troy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 16:57:31