SSE is commonly used to send message updates or continuous data streams to a browser client. In a nutshell, a server-sent event is when updates are pushed (rather than pulled, or requested) from a server to a browser.
A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
To adjust or set headers for proxied connections, use the proxy_set_header directive, followed by the header value. You can find a list of all available Request Headers and their allowed values here . If you want to prevent a header from being passed to the proxied server, set it to an empty string "" .
Your Nginx config is correct, you just miss few lines.
Here is a "magic trio" making EventSource
working through Nginx:
proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
Place them into location
section and it should work.
You may also need to add
proxy_buffering off;
proxy_cache off;
That's not an official way of doing it.
I ended up with this by "trial and errors" + "googling" :)
Another option is to include in your response a 'X-Accel-Buffering' header with value 'no'. Nginx treats it specially, see http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering
Don't write this from scratch yourself. Nginx is a wonderful evented server and has modules that will handle SSE for you without any performance degradation of your upstream server.
Check out https://github.com/wandenberg/nginx-push-stream-module
The way it works is the subscriber (browser using SSE) connects to Nginx, and the connection stops there. The publisher (your server behind Nginx) will send a POST to Nginx at a corresponding route and in that moment Nginx will immediately forward to the waiting EventSource listener in the browser.
This method is much more scalable than having your ruby webserver handle these "long-polling" SSE connections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With