Nginx中正确配置SSE(Server-Sent Events)服务

让我们深入探讨如何在Nginx中正确配置SSE(Server-Sent Events)服务。SSE是一种基于HTTP的服务器推送技术,需要特殊的Nginx配置来维持长连接。

核心配置要点

  1. 代理缓冲与分块传输
location /sse-endpoint {
    proxy_pass http://backend;
    proxy_buffering off;  # 禁用缓冲确保实时性
    proxy_cache off;      # 禁用缓存
    chunked_transfer_encoding on; # 启用分块传输
}

关键作用:proxy_buffering off确保数据立即转发而非缓冲,这对SSE的实时性至关重要。分块传输允许服务器持续发送数据片段。

  1. 超时控制
proxy_read_timeout 3600s;  # 后端读取超时(建议1小时+)
proxy_send_timeout 3600s;  # 发送超时
keepalive_timeout 3600s;   # 保持连接时间

最佳实践:SSE连接通常需要长时间保持,建议设置1小时以上。注意这些值需要大于你的预期事件间隔时间。

  1. 连接头控制
proxy_set_header Connection '';
proxy_http_version 1.1;    # 必须使用HTTP/1.1

版本差异:HTTP/1.1是SSE的必要条件,同时清空Connection头防止被转为close。

  1. 事件流头设置
add_header Content-Type 'text/event-stream';
add_header Cache-Control 'no-cache';

常见问题:缺少正确的Content-Type会导致浏览器不识别SSE流。

常见问题解决方案

连接中断问题排查:

  1. 检查Nginx日志中的upstream timed out错误
  2. 浏览器开发者工具查看SSE连接状态码
  3. 心跳机制:服务端应定期发送注释行(如: heartbeat\n\n)

代理层特殊配置:

# 针对云环境或LB的特殊配置
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
real_ip_header X-Forwarded-For;

完整配置示例


server {
    location /events {
        proxy_pass http://sse_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection '';
        proxy_set_header Host $host;
        
        proxy_buffering off;
        proxy_cache off;
        chunked_transfer_encoding on;
        
        proxy_read_timeout 24h;
        keepalive_timeout 24h;
        
        add_header Content-Type 'text/event-stream';
        add_header Cache-Control 'no-cache';
        add_header Access-Control-Allow-Origin *;
    }
}

性能考量:虽然长连接会占用资源,但现代Nginx能高效处理大量空闲连接。建议配合连接数监控(如ngx_http_stub_status_module)来评估服务器负载。

posted @ 2025-10-28 17:36  撞墙的麋鹿  阅读(7)  评论(0)    收藏  举报