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

MERN应用NGINX Location配置异常:直接访问/login报404求助

问题排查与解决方案

核心问题分析

直接输入/login访问时出现404,是因为Nginx错误地将前端路由请求转发给了后端服务,而后端并没有处理GET /login的路由;同时Nginx配置缺少对SPA单页应用路由的支持,无法在直接访问子路径时正确返回前端入口文件。

步骤1:修正Nginx配置

编辑/etc/nginx/sites-available/default,调整配置如下:

server {
    listen 80;
    server_name my_ec2_public_ip;

    # 处理前端静态文件与SPA路由
    location / {
        root /var/www/html;
        # 关键:找不到文件时返回index.html,让React路由接管
        try_files $uri $uri/ /index.html;
        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;
    }

    # 仅转发/api开头的后端接口请求
    location /api/ {
        proxy_pass http://127.0.0.1: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 /login块:/login是前端React路由,不需要转发给后端
  • 添加try_files $uri $uri/ /index.html;:确保直接访问任何前端路由时,Nginx都会返回index.html,由React路由处理跳转逻辑

步骤2:修正后端Node.js配置

编辑server/index.js,移除多余的路由挂载:

// routes
app.use("/api/auth", authRoutes);
app.use("/api/dashboard", dashboardRoutes);

// 移除以下两行:它们会导致后端接管根路径和/login路径,干扰前端路由
// app.use("/", authRoutes);
// app.use("/login", authRoutes);

const port = process.env.PORT || 5000;
app.listen(port, console.log(`Listening on port ${port}...`));
  • 后端仅需处理/api前缀的接口请求,根路径和/login路由完全由前端React接管

步骤3:重启服务使配置生效

# 重启Nginx
sudo systemctl restart nginx

# 重启pm2托管的后端服务
pm2 restart <你的后端服务名称>

验证

  • 访问EC2公网IP,确认仍能自动跳转到/login页面
  • 直接在地址栏输入http://my_ec2_public_ip/login,确认页面正常加载,不再返回404错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:27:09