【问题标题】:React Router Removes server prefix (Reverse Proxy)React Router 移除服务器前缀(反向代理)
【发布时间】:2021-09-06 11:59:55
【问题描述】:

我正在尝试在具有前缀(例如 root-prefix)和辅助前缀(例如 subdirectory/path)的反向代理服务器后面运行 React 应用程序。

最终到达网址的格式为https://myserver.com/root-prefix/subdirectory/path

我已经为子目录添加了basename

 <BrowserRouter basename="/subdirectory/path">
                <Header />
                    <Switch>
                        <Route
                            path="/componentA"
                            component={componentA}
                        />
                        <Route
                            path="/componentB"
                            component={componentB}
                        />
                    </Switch>
                <Footer />
 </BrowserRouter>

服务器 URL:https://myserver.com/root-prefix/subdirectory/path:这会呈现一个带有页眉和页脚但没有主要内容的路径。

当我点击特定的组件时,它会呈现但形式为 https://myserver.com/subdirectory/path/componentA(注意 root-prefix 已删除。)

我的nginx.conf

http {

server {

location ^~ /subdirectory/path {
      # proxy_pass ${upstream}; # Getting 502: Bad Gateway
      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;
    }
}

}

React Router 是否在内部删除 root-prefix。如果是这样,允许所有组件使用root-prefix 的方法是什么。

注意:在 Nginx 的 location 中添加前缀 root-prefix 会为整个应用程序提供 404。

【问题讨论】:

    标签: reactjs nginx react-router reverse-proxy


    【解决方案1】:

    您需要在基本名称中包含root-prefix

    <BrowserRouter basename="/root-prefix/subdirectory/path">
    

    【讨论】:

    • 我正在使用的服务器已经创建了/root-prefix。对于您的解决方案,URL 变为 https://myserver.com/root-prefix/root-prefix/subdirectory/path
    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 2017-08-16
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2020-06-29
    • 2016-09-07
    • 2020-04-19
    相关资源
    最近更新 更多