【问题标题】:Nginx: serve multiple React applications on the same serverNginx:在同一台服务器上服务多个 React 应用程序
【发布时间】:2019-10-29 00:45:19
【问题描述】:

我正在尝试在同一台服务器上设置多个 React 应用程序。问题是我构建项目后,找到了build/中的index.html,但没有找到build/static中的辅助文件。最初,只有一个应用程序,我有 location static/ 和别名。但是,对于多个项目和多个 static/ 目录,我不能这样做。基本上我希望每个应用程序都有自己的静态文件夹。我该如何解决我的问题?

在浏览器中,错误如下所示:

GET http://my.servername/static/css/2.266e55a5.chunk.css net::ERR_ABORTED 404 (Not Found)

我目前的设置是这样的:

server {
    listen   80;
    server_name my.servername;
    root   /data/adpop/;


    location /possible-malware-domains-viewer/ {
            alias /data/adpop/possible-malware-domains-viewer/build/;
            try_files $uri /possible-malware-domains-viewer/index.html;

            add_header Access-Control-Allow-Origin *;
            autoindex on;

            # Simple requests
            if ($request_method ~* "(GET|POST)") {
                    add_header "Access-Control-Allow-Origin"  *;
            }

            # Preflighted requests
            if ($request_method = OPTIONS ) {
                    add_header "Access-Control-Allow-Origin"  *;
                    add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
                    add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
                    return 200;
           }
    }

    location /punycode-domains-viewer/ {
            alias /data/adpop/punycode-domains-viewer/build/;
            try_files $uri /punycode-domains-viewer/index.html;

            [...same settings as above...]
           }
    }
}

我尝试结合来自here、here 或here 的答案,如果看起来很乱或者我有重大错误,请见谅。如果我想要实现的目标不太好,请提出其他建议。谢谢!

【问题讨论】:

  • 所以应该在多个目录下搜索以/static/开头的URI,例如: /data/foo/build/static/ 和 /data/bar/build/static/?
  • @RichardSmith 没错。每个应用都应该知道自己的静态文件夹。
  • @RichardSmith 例如,/punycode-domains-viewer/ 应用程序应在data/adpop/punycode-domains-viewer/build/static/ 中搜索其静态文件等。我不想真正混合多个应用的​​静态文件。

标签: reactjs nginx deployment nginx-location


【解决方案1】:

在多个项目和目录之间共享相同的 URI 命名空间前缀不是非常有效或可扩展的。最好给每个项目一个唯一的 URI 前缀,因此 /project1/index.html 使用像 /project1/foo.css 这样的 URI 来定位其资源。或者,为资源文件使用公共构建目录并将它们收集到构建脚本中。

但是,如果您必须将资源文件保存在单独的目录中并使用相同的 URI 前缀来引用它们,则 Nginx try_files 指令可以按顺序搜索目录,直到找到匹配的文件名。

例如:

root /data/adpop;

location /static/ {
    try_files
        /possible-malware-domains-viewer$uri
        /punycode-domains-viewer$uri
        =404;
}

将首先在 /data/adpop/possible-malware-domains-viewer/static/css/foo.css 搜索 URI /static/css/foo.css,然后在 /data/adpop/punycode-domains-viewer/static/css/foo.css 搜索。如果两个文件都没有找到,则返回 404 状态。

详情请见this document。

【讨论】:

  • 我知道这不是很有效,但这些只是一些用于显示一些结果的简单快捷的应用程序,它们很快就会改变。也许我会改变一切以使用http-server 或serve 或其他包,只使用不同的端口。感谢您的回答,刚刚试了一下,它的工作原理。
猜你喜欢
  • 2017-04-27
  • 2015-03-08
  • 2015-07-12
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2018-11-18
  • 2019-01-26
相关资源
最近更新 更多