Nginx反向代理WebSocket配置笔记

1. WebSocket协议简介

WebSocket是一种在单个TCP连接上进行全双工通信的协议,允许服务端主动向客户端推送数据。

2. Nginx配置WebSocket反向代理

基本配置

bash 复制代码
http {
    upstream websocket_backend {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }
    
    server {
        listen 80;
        server_name example.com;
        
        location /websocket/ {
            # 核心代理配置
            proxy_pass http://websocket_backend;
            
            # WebSocket必需的头信息
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header 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;
            
            # 超时设置
            proxy_read_timeout 3600s;
            proxy_send_timeout 3600s;
            proxy_connect_timeout 30s;
        }
    }
}

详细配置说明

必需的头信息配置
bash 复制代码
# 升级HTTP协议到WebSocket
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
超时配置优化
bash 复制代码
# WebSocket连接需要较长的超时时间
proxy_read_timeout 3600s;    # 读取超时
proxy_send_timeout 3600s;    # 发送超时
proxy_connect_timeout 30s;   # 连接超时
负载均衡配置
bash 复制代码
upstream websocket_cluster {
    # 负载均衡算法
    ip_hash;  # 保持会话粘性
    
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 weight=1;
    
    # 健康检查
    check interval=3000 rise=2 fall=5 timeout=1000;
}

3. 完整配置示例

单服务器配置

bash 复制代码
server {
    listen 443 ssl;
    server_name websocket.example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/private.key;
    
    location /ws {
        proxy_pass http://localhost:3000;
        
        # WebSocket升级头
        proxy_http_version 1.1;
        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;
        
        # 缓冲区设置
        proxy_buffering off;
        
        # 超时设置
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
        proxy_connect_timeout 30s;
    }
}

多服务器负载均衡

bash 复制代码
upstream websocket_servers {
    ip_hash;
    server 10.0.1.10:8080;
    server 10.0.1.11:8080;
    server 10.0.1.12:8080;
}

server {
    listen 80;
    server_name ws.example.com;
    
    location / {
        proxy_pass http://websocket_servers;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        
        # 重要:禁用缓冲区
        proxy_buffering off;
        
        # 长连接超时
        proxy_read_timeout 3600s;
    }
}

4. 高级配置选项

连接数限制

bash 复制代码
location /websocket/ {
    # 限制并发连接数
    limit_conn websocket_zone 10;
    
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

# 定义连接限制区域
limit_conn_zone $binary_remote_addr zone=websocket_zone:10m;

SSL/TLS配置

bash 复制代码
server {
    listen 443 ssl http2;
    server_name websocket.example.com;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # WebSocket over WSS
    location /wss {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

5. 常见问题排查

连接断开问题

bash 复制代码
# 增加超时时间
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;

# 保持连接活跃
proxy_set_header Connection "keep-alive, upgrade";

代理缓冲区问题

bash 复制代码
location /websocket/ {
    # 禁用缓冲区确保实时通信
    proxy_buffering off;
    proxy_buffer_size 16k;
    
    proxy_pass http://backend;
    # ... 其他配置
}

6. 性能优化建议

  1. 使用HTTP/2:提高连接效率

  2. 启用Gzip压缩:压缩文本数据

  3. 调整缓冲区大小:根据消息大小调整

  4. 使用keepalive连接:减少连接建立开销

  5. 监控连接状态:及时发现问题

7. 测试验证

使用简单的HTML页面测试WebSocket连接:

html 复制代码
<!DOCTYPE html>
<html>
<body>
<script>
const ws = new WebSocket('wss://websocket.example.com/ws');
ws.onopen = () => console.log('Connected');
ws.onmessage = (event) => console.log('Received:', event.data);
ws.onclose = () => console.log('Disconnected');
</script>
</body>
</html>

总结

Nginx作为WebSocket反向代理时,关键在于正确配置HTTP协议升级头和适当的超时设置。通过合理的负载均衡和性能调优,可以构建稳定高效的WebSocket服务架构。

相关推荐
开开心心就好7 天前
内存清理软件灵活设置,自动阈值快捷键清
运维·服务器·windows·pdf·harmonyos·risc-v·1024程序员节
学传打活9 天前
【边打字.边学昆仑正义文化】_5_宇宙物种创造简史(1)
微信公众平台·1024程序员节·汉字·昆伦正义文化
xcLeigh10 天前
打破机房围墙:VMware+cpolar构建跨网络虚拟实验室
vmware·内网穿透·cpolar·实验室·远程访问·1024程序员节
开开心心就好11 天前
免费轻量电子书阅读器,多系统记笔记听书
linux·运维·服务器·安全·ddos·可信计算技术·1024程序员节
unable code12 天前
流量包取证-大流量分析
网络安全·ctf·misc·1024程序员节·流量包取证
开开心心就好12 天前
实用PDF擦除隐藏信息工具,空白处理需留意
运维·服务器·windows·pdf·迭代器模式·桥接模式·1024程序员节
unable code13 天前
浏览器取证-[GKCTF 2021]FireFox Forensics
网络安全·ctf·misc·1024程序员节·浏览器取证
unable code13 天前
内存取证-[安洵杯 2019]Attack
网络安全·ctf·misc·1024程序员节·内存取证
unable code14 天前
CTF-SPCS-Forensics
网络安全·ctf·misc·1024程序员节·取证