nginx反向代理websocket

什么是websocket

简单来说,websocket就是建立在tcp协议之上,和http协议良好兼容的双向通信协议。
websocket同样默认使用80端口(ws)和443端口(wss)。

websocket和http的区别

websocket比http协议头部仅仅多了两个内容

1
2
Upgrade: websocket
Connection: Upgrade

nginx如何反向代理websocket

由于websocket和http协议良好兼容,于是nginx可以很好的对websocket进行代理,只需对多出来的两个头部信息进行处理就行。配置如下

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
http{
# 在http区域增加对upgrade协议的处理
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

server {
listen 80;
server_name default;

location / {
proxy_pass http://back_server;
proxy_read_timeout 300s;

# 再location中增加对websocket的转发处理
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_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
}

0%