问题描述
我正在尝试在运行 socket.io 和 express 和 nginx 的应用程序上使用 SSL,但我无法让它工作.我已经完成了我的研究,但我发现的一切都没有奏效.
I am trying to use SSL on my application running socket.io with express and nginx but I can't make it work. I have done my research but none of what I found worked.
我一直遇到错误:ERR_CONNECTION_CLOSED 客户端没有 http 状态代码.
I keep having the error : ERR_CONNECTION_CLOSED with not http status code on client side.
GET https://subdomain.mywebsite.com:1339/socket.io/?EIO=3&transport=polling&t=LIgxHmz net::ERR_CONNECTION_CLOSED
这是我的 nginx 配置:
Here is my nginx configuration :
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
Here is the client side :subdomain.mywebsite.com
var socket = io.connect("https://subdomain.mywebsite.com:1339");
页面加载良好,服务器端没有错误,但没有连接到 socket.io.在我尝试切换到 SSL 之前,一切都完美无缺.
The page loads nicely, no error on server side but no connection to socket.io.Everything worked flawlessly before I tried to switch to SSL.
我做错了什么?
推荐答案
试试这个配置.请确保拥有正确的 SSL 证书和密钥.如果您在本地测试,您可以轻松使用 mkcert 工具生成 SSL 证书以进行本地测试.
Try this configuration. Please make sure to have a correct SSL certificate and key. If you test on local you can easily use mkcert tool to generate SSL certificate to local testing.
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;
}
}
这篇关于Socket.io SSL 与 Nginx 和 Express 的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!