【问题标题】:Problem hosting react app at sub route of website - multiple websites one IP address NGINX问题在网站的子路由上托管反应应用程序 - 多个网站一个 IP 地址 NGINX
【发布时间】:2019-07-25 23:42:03
【问题描述】:

我是 NGINX 的新手,所以这可能是一个简单的修复,但我找不到任何关于我在这里尝试做什么的好文档。

所以我有一个网站,它由 nginx 和 pm2 托管在 ubuntu aws 服务器上。我的问题是我想在www.mysite.com 为网站提供服务,在www.mywebsite.com/app 提供react 应用程序。这似乎不应该是最难做的事情。但是,我一直遇到问题,无法按我的意愿工作。 (部分原因是我还希望在 www.mywebsite.com/api 托管一个 API 服务器,但这是之后的一个问题)。 我能够首先在 www.mysite.com 托管 react 应用程序以下 nginx 配置:

server {
    listen 80;
    server_name 18.191.56.251;
    root /home/ubuntu/app/src;
location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_max_temp_file_size 0;
    proxy_pass http://127.0.0.1:3000/;
    proxy_redirect off;
    proxy_read_timeout 240s;
}
}

但是当我通过更改配置将其切换到子路由时:

server {
    listen 80;
    server_name x.x.x.x;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header   X-Forwarded-Proto $scheme;

        proxy_connect_timeout       600;
        proxy_send_timeout          600;
        proxy_read_timeout          600;
        send_timeout                600;

    location /status {
        return 200;
    }

    location /app {
        proxy_pass http://127.0.0.1:3000;
    }

    location / {
        proxy_pass http://...:3011/;
    }
}

然后我的静态网站的基本路由www.mywebsite.com 工作正常,但www.mywebsite.com/app 没有并“加载”一个空白页面,但如果您检查您会发现该应用无法加载某些资源:

bundle.js:1
Failed to load resource: the server responded with a status of 404 (Not Found)
0.chunk.js:1 
Failed to load resource: the server responded with a status of 404 (Not Found)
main.chunk.js:1 
Failed to load resource: the server responded with a status of 404 (Not Found)

编辑更多研究: 如果我检查对资源的请求,我会看到它的 url 是 www.mywebsite.com/static/js/XXX.js,但静态文件夹位于 ~/app/build/static。这是托管静态文件的 nginx 还是 pm2 问题?

感谢任何帮助,谢谢

【问题讨论】:

  • 您是否尝试在proxy_pass http://127.0.0.1:3000 之后添加斜线?即 proxy_pass http://127.0.0.1:3000/

标签: reactjs amazon-web-services ubuntu nginx pm2


【解决方案1】:

所以我仍然会喜欢与此不同的结果,但我想出了一个解决方法,我在location /app 之后添加了以下内容:

location /static {
     proxy_pass http://127.0.0.1:3000;
}

我不喜欢这个解决方案,因为如果我最终将静态内容作为其他项目的一部分,那么它将无法工作,但不知何故,我网站的所有资源都打包在 / 的正确代理中。所以目前一切正常。

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多