Nginx 同时支持https与wss
2019-05-05 本文已影响60人
大猪大猪
现在几乎所有的网站都要求是https安全协议连接了、还有wss安全协议。网上的文章各种配置是超多超复杂的,这里已经对nginx指定版本进行最简单的配置,可用。

使用教程
nginx版本
$ nginx -v
nginx version: nginx/1.12.2
系统Centos7
$ uname -r
4.14.11-1.el7.elrepo.x86_64
cat /etc/nginx/conf.d/test.conf
server {
listen 80;
server_name test.dounine.com;
return 301 https://$host$request_uri;
}
server {
listen 443;
server_name test.dounine.com;
ssl on;
ssl_certificate /etc/nginx/ssls/test.xxxx.pem;
ssl_certificate_key /etc/nginx/ssls/test.xxxx.key;
location / {
client_max_body_size 100m;
proxy_pass http://localhost:7777;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
}
nodejs 代码
ws.connectSocket({
url: 'wss://test.dounine.com/ws'
});
ws.onSocketOpen(function(res) {
console.info('websocket连接成功');
});
ws.onSocketClose(function(res) {
console.log('WebSocket 已关闭!')
});
ws.onSocketError(function(res){
console.log('WebSocket连接打开失败,请检查!')
});
ws.onSocketMessage(function(res) {
console.log('收到服务器内容:' + res.data)
})