【问题标题】:Nginx, React, Node & Let's Encrypt... How to point Nginx at my React appNginx、React、Node 和 Let's Encrypt... 如何将 Nginx 指向我的 React 应用程序
【发布时间】:2017-11-09 13:47:23
【问题描述】:

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

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

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

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;
    }
}

【问题讨论】:

    标签: javascript node.js reactjs ssl nginx


    【解决方案1】:

    据我了解,您基本上是在询问如何从目录中提供静态文件。为了让 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 的静态内容作为根路由 (/)。

    注意:您可能需要更改您的 React 配置以反映添加的 /api

    【讨论】:

    • 基本上我需要的只是 /var/www/ 的内容,当您访问 myapp.com 但使用现有的 SSL 证书时提供。
    • 您需要使用第一个示例,它提供静态内容目录。有关 NGINX 指令的更多详细信息,请查看 digitalocean.com/community/tutorials/…
    • @AniSkywalker 如果我没有 index.html 只有 2 个路由路径 / 和 /api 我该如何调整我的 nginx default.conf 以便我能够访问它们?
    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多