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

React Router反向代理时丢失服务器前缀root-prefix问题咨询

不是React Router自动移除了root-prefix,问题出在路径前缀配置不完整和Nginx匹配规则不匹配两个层面,具体修复步骤如下:

1. 修正React Router basename配置

basename需要填写完整的公共路径前缀,而不是只填二级路径,修改后的代码如下:

<BrowserRouter basename="/root-prefix/subdirectory/path">
    <Header />
    <Switch>
        <Route
            path="/componentA"
            component={componentA}
        />
        <Route
            path="/componentB"
            component={componentB}
        />
        {/* 可以补充默认路由,解决首页无匹配内容的问题 */}
        <Route exact path="/">
            {/* 首页默认内容,或者配置重定向到指定路由 */}
        </Route>
    </Switch>
    <Footer />
</BrowserRouter>

此前首页仅渲染头尾的原因:你访问的路径是/root-prefix/subdirectory/path,React Router会先去掉你配置的/subdirectory/path前缀,剩余路径为/root-prefix,没有对应路由匹配,所以Switch部分没有内容输出。跳转丢失root-prefix的原因是basename没有包含该前缀,路由生成跳转路径时自然不会带上。

2. 修正打包公共路径配置

如果用的是Create React App,在package.json中新增homepage字段:

{
  "homepage": "/root-prefix/subdirectory/path"
}

如果是自定义Webpack配置,修改output.publicPath为上述路径即可,避免静态资源加载路径错误。

3. 修正Nginx配置

你之前加root-prefix前缀后报404,是因为try_files的回退路径没有对应前缀,修改后的配置如下:

http {
  server {
    # 假设站点根目录为 /usr/share/nginx/html
    root /usr/share/nginx/html;
    
    location ^~ /root-prefix/subdirectory/path {
      absolute_redirect off;
      add_header Access-Control-Expose-Headers "Origin";
      add_header Access-Control-Allow-Methods "GET,POST,PUT,DELETE";
      # 回退到对应前缀下的index.html
      try_files $uri $uri/ /root-prefix/subdirectory/path/index.html;
    }
  }
}

注意:打包后的所有静态文件需要放到服务器的/usr/share/nginx/html/root-prefix/subdirectory/path目录下,如果不想放这个目录,可以用alias指令指定静态文件路径:

location ^~ /root-prefix/subdirectory/path {
  alias /usr/share/nginx/html/; # 填写实际存放静态文件的目录
  absolute_redirect off;
  add_header Access-Control-Expose-Headers "Origin";
  add_header Access-Control-Allow-Methods "GET,POST,PUT,DELETE";
  try_files $uri $uri/ /index.html;
}

完成上述三个步骤后重新打包部署即可,所有路由都会自动带上完整的root-prefix前缀,不会丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:00:02