Nginx Proxy Configuration for Server-Sent Events (SSE) and SSL
If you are using Nginx as a reverse proxy for a backend application that streams data using Server-Sent Events (SSE), you might notice that the connection drops, buffers, or simply doesn’t stream in real-time.
To fix this, you need to configure Nginx to disable buffering and properly handle HTTP/1.1 connections for the SSE endpoint.
Here is a complete, working Nginx configuration example for proxying an application with SSE and SSL support.
upstream app_server {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# General proxy settings
location / {
proxy_pass http://app_server;
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;
}
# SSE specific endpoint configuration
location /api/stream {
proxy_pass http://app_server;
proxy_set_header Host $host;
# Crucial for Server-Sent Events
proxy_http_version 1.1;
proxy_set_header Connection "";
# Disable buffering to allow real-time streaming
proxy_buffering off;
proxy_cache off;
# Increase timeouts for long-lived connections
proxy_read_timeout 24h;
proxy_send_timeout 24h;
}
}
Key Configuration Directives for SSE
-
proxy_http_version 1.1;andproxy_set_header Connection "";Nginx defaults to HTTP/1.0 for proxying, which closes the connection after the response is sent. SSE requires a persistent HTTP/1.1 connection with chunked transfer encoding. -
proxy_buffering off;By default, Nginx buffers responses from the proxied server. This ruins SSE because Nginx will hold onto the event chunks until the buffer is full before sending them to the client. Disabling buffering ensures chunks are delivered to the client immediately. -
proxy_read_timeout 24h;Since SSE connections are designed to stay open for a long time, the default Nginx read timeout (usually 60 seconds) will kill the connection if the server doesn’t send an event for a minute. Setting this to a high value prevents unexpected disconnects.