首页 > 解决方案 > 如何将静态资产 (html) 提供给使用 nginx 运行的节点服务器?

问题描述

我有一台运行 pm2 的服务器,由 nginx 提供服务。我想将我的反应应用程序指向域,并让服务器只响应客户端发送的请求。

目前,如果您访问 jwcuisine.io,它会给您一条“CANNOT GET /”消息,我尝试过这样的操作:

location / {
    # This would be the directory where your React app's static files are stored at
    root /var/www/html/;
    try_files $uri /index.html;
} 

 location /graphql {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:5000/;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
} 

但是,上面的 ^^^ 导致来自 nginx 的 500 错误。

下面是我目前拥有的代码,它给出 /GET 响应。任何方向将不胜感激,我找不到与此相关的大量相关信息。

server {
    server_name jwcuisine.io www.jwcuisine.io;

    location / {
        proxy_pass http://localhost:4000; #whatever port your app runs on
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/jwcuisine.io/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/jwcuisine.io/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.jwcuisine.io) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = jwcuisine.io) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 default_server;
    listen [::]:80 default_server;

    server_name jwcuisine.io www.jwcuisine.io;
    return 404; # managed by Certbot
}

标签: node.jsreactjsexpressnginx

解决方案


我也使用类似的架构通过 nginx 反向代理服务器托管我的网站前端和后端。您的 nginx conf 中有一个更新,之后它将按预期工作。也就是说,您需要首先添加所有子路由(例如/apigraphql),然后您需要添加索引路由的位置//server在您当前的 conf 网站中,由于路由首先与索引路由匹配,因此将永远无法访问服务器,/并且它将尝试在静态文件夹中找到它,并且永远不会到达proxy_pass您在以下位置提供的内容。

更新 nginx.conf:

server{
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name jwcuisine.io www.jwcuisine.io;

    location /graphql {
        proxy_pass "http://127.0.0.1:5000";
        proxy_read_timeout 5400s;
        proxy_send_timeout 5400s;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_cache_bypass $http_upgrade;
    }


    location / {
        root /var/www/html;
        try_files $uri $uri/ /index.html;
    }
}


推荐阅读