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

React嵌套路由在Nginx部署的VPS上显示空白问题求助

MERN应用Nginx部署后嵌套路由空白问题排查方案

1. 核心问题本质

React这类单页应用的路由属于前端路由,本地开发时依赖React Dev Server自动将所有路由请求转发到index.html,但Nginx默认会把/dashboard/users这类路径当成服务器上的文件/目录去查找,找不到就返回404,最终导致空白页面。

2. Nginx配置修正(关键)

检查你的主机配置,必须加路由转发规则,确保所有非API的GET请求都指向index.html,让前端路由处理。标准配置示例:

server {
    listen 80;
    server_name 你的域名或IP;

    # 指向React build后的静态文件目录
    root /var/www/你的应用目录/build;
    index index.html;

    # 核心规则:处理前端路由
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 如果有后端API,单独转发(按需配置)
    location /api {
        proxy_pass http://localhost:5000; # 后端服务端口
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    # 静态资源缓存优化(可选)
    location ~* \.(js|css|png|jpg|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

重点是try_files $uri $uri/ /index.html;这一行,优先级为:先找对应文件→找不到找目录→最后返回index.html。

3. React路由配置检查

确保使用BrowserRouter而非HashRouter(HashRouter带#号路由,不会触发Nginx文件查找,但生产环境一般用BrowserRouter):

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="dashboard" element={<Dashboard />}>
          <Route path="users" element={<Users />} />
          {/* 其他嵌套路由 */}
        </Route>
      </Routes>
    </Router>
  );
}

同时确认package.json的build脚本正确(Create React App项目默认是"build": "react-scripts build"),执行npm run build后生成的build目录完整。

4. .env配置排查

如果部署在根路径下,不要设置PUBLIC_URL,或者将其设为/:

# 错误示例:不要设置为具体域名或子路径(除非确实部署在子路径)
# PUBLIC_URL=https://your-domain.com
PUBLIC_URL=/

若部署在子路径(如your-domain.com/app),则需设置PUBLIC_URL=/app,同时Nginx的location要对应调整为/app并转发。

5. 后续验证步骤

  1. 检查Nginx配置语法:sudo nginx -t
  2. 重启Nginx:sudo systemctl restart nginx
  3. 强制刷新浏览器(Ctrl+Shift+R),清理缓存
  4. 若仍有问题,查看Nginx错误日志排查:sudo tail -f /var/log/nginx/error.log
  5. 确认build目录权限:sudo chown -R www-data:www-data /var/www/你的应用目录/build && sudo chmod -R 755 /var/www/你的应用目录/build

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:00:54