node.js - 如何将静态资产 (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
}
解决方案
我也使用类似的架构通过 nginx 反向代理服务器托管我的网站前端和后端。您的 nginx conf 中有一个更新,之后它将按预期工作。也就是说,您需要首先添加所有子路由(例如/api
,graphql
),然后您需要添加索引路由的位置/
。/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;
}
}
推荐阅读
- c# - 在视图中呈现时自动关闭 html 标签?
- powershell - 将每行的字符串移动到特定位置
- java - 比较多个动态数组的每个元素
- swift - DatePickerDialog 仅显示最小日期
- python - 如何强制 xlwings 使用 COMRetryObjectWrapper 而不是 win32com api?
- python - 如何在定义自己的函数时迭代列表中的条目
- google-apps-script - 使用 Google 脚本从地址数据中获取地理位置数据
- firebase - 从登录用户创建的 Firebase 中读取数据 - Flutter
- python - 如何在小部件删除操作后使 Tkinter 小部件粘在窗口边框上?
- c# - Clipboard.SetContent 中的错误