首页 > 解决方案 > 将 React 应用程序作为 nginx 中的子路径提供服务

问题描述

有一个在0.0.0.0:5000本地提供的 React 应用程序。我也有一个域名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/(.*) /$1 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

我如何解决它 ?

标签: javascriptreactjsnginxmod-rewritecreate-react-app

解决方案


nginx 配置对我来说看起来不错,但是您需要更新 webpack 配置以及 React 应用程序中的路由器配置,以便在特定路径上为应用程序提供服务。

我不能对以下要点表示任何赞赏,但它涵盖了您应该需要的所有情况:

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

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


推荐阅读