Nginx 代理 WebSocket 的要点是设置Upgrade
和Connection
响应头。
配置 Nginx 根据Upgrade
(即$http_upgrade
)来设置Connection
:
- 如果请求头中有
Upgrade
,就直接设置到相应头中,并把Connection
设置为upgrade
。如 WebSocket 请求头会带上Upgrade: websocket
,则响应头有Upgrade: websocket Connection: upgrade
- 否则把
Connection
设置为close
。如普通HTTP请求。
最终 Nginx 配置如下:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 8000;
location / {
proxy_pass http://localhost:4000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
网友评论