如何使用 nginx 设置安全的 websocket

Posted

技术标签:

【中文标题】如何使用 nginx 设置安全的 websocket【英文标题】:How to setup secure websockets with nginx 【发布时间】:2019-04-16 00:07:05 【问题描述】:

我有一个在端口 9000 上运行的网络服务器,我想让它在端口 80 上可用,并且我想在端口 9021 上提供一个 websocket 连接。如果我在http 上运行它,一切正常。但是当我去https时,websocket无法连接。

这是我的 nginx 配置:这给出了警告:

nginx: [warn] conflicting server name "oyun.net" on 0.0.0.0:443, ignored

server 
     listen 443 ssl;
     server_name          oyun.net;
     ssl_certificate      /etc/key.pem
     ssl_certificate_key  /etc/key2.pem
     listen 80;
     location / 
         proxy_pass http://localhost:9000
     


server 
     listen 443 ssl;
     server_name          oyun.net;
     ssl_certificate      /etc/key.pem
     ssl_certificate_key  /etc/key2.pem
     listen 9021;
     location / 
        proxy_pass http://localhost:9000;
        proxy_http_version 1.1;
        proxy_set_header upgrade $http_upgrade;
        proxy_set_header connection "upgrade";
        proxy_set_header x-real-ip $remote_addr;
        proxy_set_header host $host;
        proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
     
 

这是浏览器错误:

WebSocket connection to 'wss://oyun.net:9021/socket/v1?sri=tcylqwzjnl' failed: 

Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR

【问题讨论】:

【参考方案1】:

我为 socket.oyun.net 创建了一个新的认证,这个配置有帮助

server 
        listen 80;
        server_name oyun.net;
        return 301 https://oyun.net$request_uri;


server 
        listen 443 ssl;
        server_name oyun.net;
        ssl_certificate         /etc/letsencrypt/live/oyun.net/fullchain.pem;
        ssl_certificate_key     /etc/letsencrypt/live/oyun.net/privkey.pem;

        location / 
                proxy_pass http://localhost:9000;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        


server 
        listen 9021 ssl;
        server_name socket.oyun.net;
        ssl_certificate         /etc/letsencrypt/live/socket.oyun.net/fullchain.pem;
        ssl_certificate_key     /etc/letsencrypt/live/socket.oyun.net/privkey.pem;


        location / 

                proxy_pass http://localhost:9000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header X-Real-Ip $remote_addr;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


        


【讨论】:

以上是关于如何使用 nginx 设置安全的 websocket的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 nginx 设置安全的 websocket

服务器网站安全维护之nginx安全设置篇

websock第一次连不上window

通过 nginx 或 traefik 通过 html 网页访问 docker 容器 websocket?

如何设置nginx和apache

织梦Dedecms使用Nginx的安全设置