与Nginx和Express的Socket.io SSL连接

时间:2016-05-13 16:39:03

标签: node.js ssl express nginx socket.io

我正在尝试在运行带有express和nginx的socket.io的应用程序上使用SSL,但我无法使其正常工作。我完成了我的研究,但没有发现我的工作。

我一直有错误:ERR_CONNECTION_CLOSED而不是客户端的http状态代码。

GET https://subdomain.mywebsite.com:1339/socket.io/?EIO=3&transport=polling&t=LIgxHmz net::ERR_CONNECTION_CLOSED

这是我的nginx配置:

server {
listen 443;
server_name subdomain.mywebsite.com;

root /usr/share/nginx/html;
index index.html index.htm;

ssl on;
# Use certificate and key provided by Let's Encrypt:
ssl_certificate /etc/letsencrypt/live/subdomain.mywebsite.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/subdomain.mywebsite.com/privkey.pem;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://localhost:1339/;
    proxy_redirect off;

    # Socket.IO Support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

这是服务器端:

var express = require('express'),

var app = express();

var server = require('http').createServer(app);
var io = require('socket.io')(server);

server.listen(1339);

...

以下是客户端: subdomain.mywebsite.com

var socket = io.connect("https://subdomain.mywebsite.com:1339");

页面加载很好,服务器端没有错误,但没有连接到socket.io。 在我尝试切换到SSL之前,所有工作都完美无缺。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试此配置。请确保拥有正确的SSL证书和密钥。如果您在本地进行测试,则可以轻松地使用mkcert工具生成用于本地测试的SSL证书。

server {
   listen 80;
   server_name <your server_name>;
   return 301 https://<your server_name>$request_uri;
}

server {
   listen 443 ssl;


   ssl_certificate <your certificate path>;  # better if you put them at /etc/nginx/ssl/
   ssl_certificate_key <your certificate_key path >;

   server_name <your server_name>;

   location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $remote_addr;
      proxy_set_header X-Client-Verify SUCCESS;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_pass http://localhost:3000;
      proxy_redirect off;
      proxy_buffering off;
   }
}