将 React 应用程序作为 nginx 中的子路径

Serve React application as sub path in nginx

有一个 React 应用程序在 0.0.0.0:5000 本地服务。 我还有一个域名 example.com.

我想做的是将 example.com/app 目录代理到 0.0.0.0:5000.

我尝试了以下方法。

location /app  {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_redirect     off;
    proxy_set_header   Host $host;
    rewrite /app/(.*) / break;
    proxy_pass http://0.0.0.0:5000/app;

}

但是在控制台中错误显示如下

Loading failed for the <script> with source “http://localhost/static/js/bundle.js”. app:45:1
Loading failed for the <script> with source “http://localhost/static/js/0.chunk.js”. app:45:1
Loading failed for the <script> with source “http://localhost/static/js/main.chunk.js”.

我也尝试将 homepage: './app 添加到 package.json

我该如何解决?

我认为 nginx 配置没问题,但您需要更新 webpack 配置以及 React 应用程序中的路由器配置,以便在特定路径上为应用程序提供服务。

我不能相信以下要点,但它涵盖了您应该需要的所有情况:

https://gist.github.com/codepunkt/ae82a0f3b9deb93908dc1f3d5bbc8da2

(注意你的basePath应该以“/”开头,比如“/app”)