nginx的websocket

WebSocket 通过 HTTP 的 Upgrade 机制实现协议切换:

初始请求是 HTTP 请求

通过特定的头部告知服务器要进行协议升级

服务器返回 101 Switching Protocols 状态码后,连接转为 WebSocket 协议

image

标准的配置

location /ws/ {
    proxy_pass http://websocket_backend;
    proxy_http_version 1.1;
    
    # WebSocket必需的头部
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    
    # 传递真实客户端信息
    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_set_header X-Forwarded-Proto $scheme;
    
    # 超时设置(WebSocket长连接)
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;      # 关键:WebSocket心跳间隔
}

# 在http块中定义connection_upgrade映射
#这是一个动态映射:如果请求头中有 $http_upgrade(即客户端发送了 Upgrade 头),则设置 $connection_upgrade 为 upgrade,否则为 close
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
posted @ 2026-04-01 13:38  爱晒太阳的懒猫。。  阅读(14)  评论(0)    收藏  举报