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

Nginx路由配置问题:根路径返回静态页,其余转发至React容器

问题分析与解决方案

你的问题核心是location = /里的try_files指令触发了内部重定向,导致请求被转交到location /处理,而非返回静态文件。虽然location = /的优先级确实最高,但try_files $uri /index.html;中的/index.html会发起内部跳转,这个跳转请求会匹配到location /规则,最终被代理到React容器。

修复后的配置

修改location = /块,移除多余的try_files(index指令已经会自动加载指定的索引文件),或者调整try_files避免跨location跳转:

server {
    listen 443 ssl;
    server_name myhost.com;

    # SSL Configuration (unchanged)
    # ...

    # Serve Marketing Site for /
    location = / {
        root /var/www/html;
        index index.html;
        # 如需额外文件检查,可替换为下方注释行,避免跨location跳转
        # try_files $uri =404;
    }

    # Serve React App
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        error_page 404 =200 /index.html;
    }
}

关键说明

  • index index.html指令在请求路径为/时,会自动尝试加载root目录下的index.html,无需额外的try_files。
  • 原配置中的try_files $uri /index.html会在$uri(即/)对应的目录存在时,仍发起/index.html的内部请求,而这个请求会被location /捕获,从而走代理流程。
  • 若需要对location = /做文件存在性校验,使用try_files $uri =404;即可,不会触发跨location的内部跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:32:39