使用来自 certbot 的 ssl 将 websocket nginx 代理设置为 node.js

Setup websocket nginx proxy to node.js using ssl from certbot

我想通过使用 ws npm 模块的节点应用程序使用 ssl websockets (wss://)。最重要的是,我想使用我通过 certbot 的 nginx 设置的 ssl。

我在端口 8080 上侦听节点 websocket,虽然我可以直接连接到该端口,但由于该站点是通过 ssl 提供服务的,因此会引发错误,因为它未加密。

对于客户端 javascript,您可以将调用路由到 wss://examplesite。com/websocket

  • 在 nginx 配置中,将连接设置为在 header 设置为 '' 时关闭。
  • 为您的 websocket 端口创建一个上游
  • 添加 /websocket 位置

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

upstream websocket {
   server 127.0.0.1:8080;
}

server {
    server_name examplesite.com;
    location /websocket {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header Host $host;
    }

# after this is just an example of the rest of the nginx config for a node server on 8675
# that has a static build directory
    location / {
        proxy_pass http://127.0.0.1:8675;
        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;
        proxy_set_header X-Real-IP $remote_addr;
    }
    location ~ \.(gif|jpg|png|js|txt|html|mp3|css|woff2)$ {
        root /root/examplesite.com/build/;
        expires 30d;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/examplesite.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/examplesite.com/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

}

您可以使用 https://www.npmjs.com/package/wscat 测试本地 ws://...:8080 和 wss://.../websocket 连接