nginx 配置websocket

时间:2022-07-22
本文章向大家介绍nginx 配置websocket,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Nginx 代理 WebSocket 的要点是设置Upgrade和Connection响应头。 配置 Nginx 根据Upgrade(即$http_upgrade)来设置Connection:

如果请求头中有Upgrade,就直接设置到响应头中,并把Connection设置为upgrade。如 WebSocket 请求头会带上Upgrade: websocket,则响应头有

Upgrade: websocket
Connection: upgrade

否则把Connection设置为close。如普通HTTP请求。 最终 Nginx 配置如下:

nginx.conf 中 http 配置

map $http_upgrade $connection_upgrade {
  default upgrade;
  '' close;
}

conf.d下的.conf具体配置文件

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;
  }
}