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

Nginx部署多React应用问题:访问子路径显示空白页求助

解决React子应用Nginx配置后空白页的问题

首先咱们来拆解下你当前配置的核心问题:

  • 你使用了permanent永久重定向,这会让浏览器地址栏直接跳转到/react-referral/build/,既暴露了服务器内部的文件路径,更关键的是React打包后的静态资源路径会完全不匹配。React默认打包时,静态资源(比如static/js/main.*.js、static/css/main.*.css)的引用是基于应用根路径设置的,当URL变成/react-referral/build/后,页面会尝试请求http://x.x.x.x/static/js/...,但这些资源实际在/home/ubuntu/team/react-referral/build/static/目录下,Nginx找不到资源,页面自然就空白了。
  • 另外,React是单页应用(SPA),需要Nginx正确处理路由跳转,确保子路径下的所有路由都能指向对应的index.html。

修正后的Nginx配置

把你的server块修改成下面这样,用alias映射子应用的静态目录,同时保留正确的路由处理逻辑:

server {
    listen 80 default_server;
    root /home/ubuntu/team;
    index index.html index.htm index.nginx-debian.html;
    server_name x.x.x.x;

    # 主应用路由处理(如果存在主应用的话)
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 处理referral子应用
    location /referral {
        alias /home/ubuntu/team/react-referral/build;
        try_files $uri $uri/ /referral/index.html;
    }

    # 处理fulfillment子应用
    location /fulfillment {
        alias /home/ubuntu/team/react-fulfillment/build;
        try_files $uri $uri/ /fulfillment/index.html;
    }

    # 处理leader子应用
    location /leader {
        alias /home/ubuntu/team/react-leader/build;
        try_files $uri $uri/ /leader/index.html;
    }
}

关键配置说明

  • alias:这个指令会把location匹配的路径替换成指定的目录路径。比如访问/referral/时,Nginx会直接去/home/ubuntu/team/react-referral/build/目录下找文件,完美对应你的子应用打包目录。
  • try_files $uri $uri/ /referral/index.html:优先尝试访问请求的文件或目录,如果找不到,就返回子应用的index.html,这样React的路由就能正常接管所有子路径的跳转了。

后续验证步骤

  1. 保存修改后的配置文件,重启Nginx让配置生效:
    sudo systemctl restart nginx
    
  2. 清除浏览器缓存(或者用无痕模式打开),访问http://x.x.x.x/referral/,现在地址栏应该保持/referral/不变,页面也能正常加载了。
  3. 打开浏览器开发者工具的「网络」标签,检查所有静态资源的请求状态都是200,没有404错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:48:55