首先在服务端假如使用了socket.io,并且相关代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14const express = require('express');
global.express = express;
global.app = express();
const io = require('socket.io');
console.log('web server listen on 127.0.0.1:8000');
let server = global.app.listen(8000, '127.0.0.1');
global.io = io(server,{
upgrade: false,
transports: ['websocket'],
reconnection: true,
});
...
此时我们将socket.io
的监听绑定到express
上,这样避免了重新开辟一条通路。
接着在/etc/nginx/conf.d/
下创建一个站点的配置文件:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42upstream www {
server 127.0.0.1:8000;
}
server {
listen 80;
# 修改为自己的域名
server_name www.example.cn;
# 301 重定向
return 301 https://www.example.cn$request_uri;
}
server {
listen 443;
server_name www.example.cn;
ssl on;
# 证书路径不要写错
ssl_certificate /etc/nginx/ssl/1_example.cn_bundle.crt;
ssl_certificate_key /etc/nginx/ssl/2_example.cn.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
if ($ssl_protocol = "") {
rewrite ^(.*) https://$host$1 permanent;
}
location / {
# WebSocket 配置
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Nginx-proxy true;
# 这里也要修改为你的二级域名前缀
proxy_pass http://www;
proxy_redirect off;
}
}
检查配置文件是否正确:1
2
3$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新启动Nginx:1
sudo nginx -s reload
此时我们就能使用HTTPS下的websocket了。
为了让我们的服务更加的稳定,可以使用pm2
来管理node项目。1
npm install pm2 -g