以下是一个关于Nginx支持WebSocket协议的详细配置示例,涵盖基础配置、安全防护、负载均衡及监控方案:
一、基础WebSocket配置
1. 反向代理配置
http {
upstream websocket_backend {
server 192.168.1.100:8080; # WebSocket服务端地址
keepalive 32; # 保持32个长连接
}
server {
listen 80;
server_name ws.example.com;
location /ws/ {
# 基础代理配置
proxy_pass http://websocket_backend;
proxy_http_version 1.1; # 必须使用HTTP/1.1
proxy_set_header Upgrade $http_upgrade; # 升级协议头
proxy_set_header Connection "upgrade"; # 保持长连接
# 超时设置(根据业务需求调整)
proxy_read_timeout 86400; # 24小时超时(适合实时通信)
proxy_send_timeout 86400;
# 缓冲区配置(优化大消息传输)
proxy_buffering off; # 禁用缓冲(实时性要求高)
proxy_buffer_size 16k;
proxy_busy_buffers_size 32k;
}
}
}
2. HTTPS强制配置
server {
listen 443 ssl;
server_name wss.example.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 重定向所有HTTP请求到HTTPS
if ($scheme = http) {
return 301 https://$host$request_uri;
}
}
}
二、高级功能扩展
1. 负载均衡配置
http {
upstream websocket_pool {
# 权重轮询(默认)
server 192.168.1.100:8080 weight=5;
server 192.168.1.101:8080 weight=3;
# 会话保持(基于Cookie)
sticky cookie srv_id expires=1h domain=.example.com path=/;
# 健康检查
health_check interval=10s fails=3 passes=2;
}
server {
listen 443 ssl;
server_name wss.example.com;
location /ws/ {
proxy_pass http://websocket_pool;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
2. 消息压缩配置
http {
# 启用Brotli压缩(需编译支持)
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/javascript application/json;
server {
listen 443 ssl;
server_name wss.example.com;
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 压缩配置
proxy_set_header Accept-Encoding "gzip, deflate, br";
proxy_pass_request_headers on;
}
}
}
三、安全加固配置
1. 访问控制
server {
listen 443 ssl;
server_name wss.example.com;
location /ws/ {
# IP白名单
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
# 请求大小限制
client_max_body_size 10M;
client_body_buffer_size 5M;
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
2. 防DDoS攻击
http {
limit_req_zone $binary_remote_addr zone=ws_limit:10m rate=50r/s; # 全局限速
server {
listen 443 ssl;
server_name wss.example.com;
location /ws/ {
limit_req zone=ws_limit burst=100 nodelay; # 突发100请求
limit_conn conn_limit 200; # 单IP最大200连接
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
四、监控与维护配置
1. 实时状态监控
http {
server {
listen 8080;
server_name status.example.com;
location /ws_status {
# 自定义WebSocket状态页(需Lua模块)
content_by_lua_block {
local connections = ngx.shared.ws_connections
ngx.say("Active connections: ", connections.active)
ngx.say("Total connections: ", connections.total)
}
allow 192.168.1.0/24;
deny all;
}
}
}
2. 详细日志记录
http {
log_format ws_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$upstream_addr $request_time '
'$upstream_response_time $upstream_status';
access_log /var/log/nginx/ws_access.log ws_log;
}
五、性能调优建议
-
内核参数优化
# 调整文件描述符限制 ulimit -n 65535 # 优化TCP参数 sysctl -w net.core.somaxconn=65535 sysctl -w net.ipv4.tcp_max_syn_backlog=65535 sysctl -w net.ipv4.tcp_fin_timeout=30
-
Nginx配置优化
- 调整
worker_processes
匹配CPU核心数 - 启用
sendfile on
提升文件传输效率 - 使用
tcp_nopush
和tcp_nodelay
优化TCP传输
- 调整
-
连接管理
- 定期执行
nginx -s reload
清理僵尸连接 - 使用
proxy_ignore_client_abort on
防止客户端异常断开
- 定期执行
六、测试与验证
-
连接测试
# 使用wscat工具测试WebSocket连接 wscat -c wss://wss.example.com/ws/
-
压力测试
# 使用websocket-bench进行压力测试 websocket-bench -a 100 -c 10 -y 3600 wss://wss.example.com/ws/
-
实时监控
# 观察活跃连接数 ss -s | grep websocket # 分析访问日志 awk '/GET \/ws\//' /var/log/nginx/ws_access.log | wc -l
该配置示例实现了WebSocket协议的核心功能,可根据实际需求扩展以下方向:
- 集成JWT/OAuth2认证(需Lua模块)
- 添加消息路由(通过WebSocket子协议)
- 实现消息持久化(需Redis/Kafka集成)
- 配置服务发现(与Consul/Etcd集成)
建议通过专业测试工具(如JMeter)验证配置效果,并结合APM工具(如Prometheus+Grafana)构建完整监控体系。