gpt4 book ai didi

javascript - Nginx、React、Node & Let's Encrypt……如何将 Nginx 指向我的 React 应用程序

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:45 25 4
gpt4 key购买 nike

我有一个 React 应用程序,我需要与运行在端口 5000(通过 pm2)上的 Node 服务器通信并成为根我网站的目录。 Node 服务器从 API 获取一些数据并将其返回给客户端。现在,我让 Nginx 指向端口 5000(我按照教程到达这一点作为测试)。

假设我的 React 应用程序位于/www/ReactApp/dist/,我如何将 Nginx 指向那里而不是端口 5000 上的 Node 服务器?

基本上我需要的是当您访问 myapp.com 但使用现有 SSL 证书时提供的/www/ReactApp/dist/的内容。

Node server.js 将仅在后台运行,我的 React 应用程序将调用它以获取数据。

这是我的/etc/nginx/sites-enabled/default 的内容:

# HTTP — redirect all traffic to HTTPS
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://$host$request_uri;
}

# HTTPS — proxy all requests to the Node app
server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name myapp.com;

# Use the Let’s Encrypt certificates
ssl_certificate /etc/letsencrypt/live/myapp.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem;

# Include the SSL configuration from cipherli.st
include snippets/ssl-params.conf;

location / {
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;
}
}

最佳答案

据我了解,您基本上是在询问如何从目录提供静态文件。为了让 React 应用程序(客户端)调用 Node 后端(服务器端),两者都需要公开。您应该像这样添加一个 NGINX 指令:

location / {
# Set this to the directory containing your React app's index.html.
root /var/www/;
try_files $uri /index.html;
}

然后,对于 Node 服务器,您将保留您拥有的内容,但将其放在不同的路径中,如下所示:

location /api {
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;
}

这会将 /api 代理到您的 Node 服务器,同时将 /var/www 的静态内容作为根路由 (/)。

NOTE: You might need to change your React configuration to reflect the /api addition.

关于javascript - Nginx、React、Node & Let's Encrypt……如何将 Nginx 指向我的 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com