在使用了Nginx做负载均衡之后,那么原先的WebSocket将没法连接到服务器(废话!),那么我们需要配置Nginx,将WebSocket请求也进行反向代理。

nginx.conf配置:

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
42
43
44
45
#websocket配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

server {
listen 801;
server_name localhost;
#布置websocket处理服务器
location / {
proxy_pass http://127.0.0.1:8110;

#配置Nginx支持webSocket开始
proxy_set_header Host $http_host;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}

server {
listen 4431;
server_name localhost;
ssl on;
root html;
ssl_certificate cert/XXXXXXXXX.pem;
ssl_certificate_key cert/XXXXXXXXX.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 SSLv2 SSLv3;
ssl_prefer_server_ciphers on;
#布置websocket处理服务器
location / {
proxy_pass http://127.0.0.1:8110;

#配置Nginx支持webSocket开始
proxy_set_header Host $http_host;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}

客户端连接时,就使用ws和wss协议分别连接以上的801和4431端口。
更多文章,请关注:开猿笔记