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

使用Nginx作为反向代理部署React应用出现空白页问题求助

问题根源

你的Nginx路由匹配规则存在逻辑冲突:

  • location = /仅精准匹配根路径,此时会返回前端的index.html
  • 其余所有路径(包括React打包生成的/static/js/*.js、/static/css/*.css等静态资源请求)都会被location /规则匹配,直接转发到FastAPI后端,后端不存在这些静态资源,因此返回404导致React无法加载完整资源出现空白页。

解决方案

推荐使用前后端路径分离的配置方案,逻辑清晰不易出现冲突:

步骤1:调整Nginx配置

将以下内容替换你的原有Nginx配置:

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2;
    server_name pbl.asia www.pbl.asia;
    server_tokens off;

    root /usr/share/nginx/html;
    index index.html index.htm;

    # 处理站点图标
    location = /favicon.ico {
        root /usr/share/nginx/html;
    }

    # 匹配React静态资源,添加缓存规则提升加载速度
    location ~* ^/static/ {
        root /usr/share/nginx/html;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # 前端路由 fallback,所有前端页面请求都返回index.html交给React路由处理
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 仅将/api开头的请求转发到FastAPI后端
    location /api/ {
        proxy_set_header    Host                $http_host;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_pass "http://backend:8000/";
    }

    ssl_certificate /etc/letsencrypt/live/pbl.asia/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/pbl.asia/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

步骤2:修改后端接口前缀

在FastAPI初始化时添加root_path参数,统一接口前缀:

from fastapi import FastAPI
app = FastAPI(root_path="/api")
# 其余代码保持不变

同时前端调用后端接口时,统一使用/api/xxx的路径格式。

步骤3:重启Nginx生效

执行以下命令重启Nginx容器加载新配置:

docker-compose restart nginx

可选替代方案(无需改后端代码)

如果不想调整后端接口前缀,可以用以下Nginx配置,优先读取本地静态文件,不存在的请求再转发到后端:

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2;
    server_name pbl.asia www.pbl.asia;
    server_tokens off;

    root /usr/share/nginx/html;
    index index.html index.htm;

    location = /favicon.ico {
        root /usr/share/nginx/html;
    }

    location / {
        try_files $uri $uri/ @backend;
    }

    location @backend {
        proxy_set_header    Host                $http_host;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_pass "http://backend:8000";
    }

    ssl_certificate /etc/letsencrypt/live/pbl.asia/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/pbl.asia/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:42:03