basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    Reverse proxy in nginx: Node, Python, Go, WebSocket, and SSE streaming

    Line-by-line reverse proxy configs: forwarding client IP and headers to your app, trailing-slash rules in proxy_pass, WebSockets via map, and disabling buffering for SSE and AI chat streams.

    Shared proxy headers snippet

    A Node.js, Python (Gunicorn, Uvicorn), or Go app bound to 127.0.0.1 (0.0.0.0 vs 127.0.0.1) sees every request as coming from 127.0.0.1, with Host: 127.0.0.1:3000 and scheme http, unless the proxy passes the original values. By default, nginx also speaks HTTP/1.0 to backends and closes the connection after each response.

    Put the baseline directives in /etc/nginx/snippets/proxy-headers.conf. The reason matches add_header: proxy_set_header is an array directive, so adding one proxy_set_header inside a location drops every proxy_set_header inherited from server (Config anatomy). Pulling in a snippet with include avoids that trap.

    /etc/nginx/snippets/proxy-headers.conf
    proxy_http_version 1.1;

    Switches upstream requests to HTTP/1.1: required for WebSockets, backend keepalive pools, and chunked streaming.

    default:proxy_http_version 1.0

    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;
    Key part

    Forwards the browser’s original Host (otherwise nginx sends $proxy_host, like 127.0.0.1:3000), client IP, proxy chain, and original scheme (http or https).

    default:Host $proxy_host

    If Cloudflare or another proxy sits in front of nginx, extract the real client IP with ngx_http_realip_module — covered in the rate-limiting and access guide.

    Setup 1: reverse proxy to a web app (Node, Python, Go)

    A baseline config for an app on 127.0.0.1:3000, plus a second /strip/ route showing trailing-slash prefix removal and timeouts.

    /etc/nginx/conf.d/app.example.org.conf
    server {
        listen 80;
        server_name app.example.org;
        client_max_body_size 16m;

    Accepts traffic for the domain and raises the request body cap to 16m (the 1m default rejects most image uploads and attachments).

    default:client_max_body_size 1m

        location / {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            proxy_pass http://127.0.0.1:3000;
    Key part

    Includes the shared snippet and clears Connection so nginx doesn’t send Connection: close and can reuse backend TCP sockets. Omitting a trailing slash on proxy_pass forwards the request path as-is.

            proxy_connect_timeout 10s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

    Timeouts for connecting, sending the request, and reading the response. Lowering proxy_connect_timeout to 5–10s avoids leaving users hanging for a full minute if the app is down.

    default:proxy_connect_timeout 60sproxy_send_timeout 60sproxy_read_timeout 60s

        location /strip/ {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            proxy_pass http://127.0.0.1:4000/;
        }
    }

    A separate service on port 4000 unaware of the /strip/ prefix: the trailing slash on proxy_pass strips /strip/ from the URI. /strip/users reaches the app as /users.

    Trailing slash in proxy_pass: keep or strip the prefix

    One trailing / on proxy_pass changes the URI your backend receives:

    location proxy_pass Client request URI sent to backend
    location /api/ http://127.0.0.1:3000; (no path) /api/users /api/users — passed unchanged
    location /api/ http://127.0.0.1:3000/; (has /) /api/users /users — /api/ replaced with /
    location /api/ http://127.0.0.1:3000/v2/; /api/users /v2/users — /api/ replaced with /v2/
    location /api (no /) http://127.0.0.1:3000/; (has /) /api/users //users — double slash from mismatched /

    Setup 2: WebSocket without breaking regular HTTP

    A WebSocket starts as an HTTP/1.1 request carrying Upgrade: websocket and Connection: Upgrade. Hardcoding proxy_set_header Connection "upgrade"; in a shared location sends that header on normal HTTP requests too — some app servers reject it or break keep-alive.

    Use a map block in http instead: forward upgrade only when the client sent an Upgrade header, otherwise send close (or "" if proxying to an upstream with keepalive).

    /etc/nginx/conf.d/ws.example.org.conf
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
    Key part

    Lives in the http context (outside server). $connection_upgrade evaluates to upgrade only when the request includes an Upgrade header.

    server {
        listen 80;
        server_name ws.example.org;
    
        location /ws {
            include snippets/proxy-headers.conf;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;

    Dedicated WebSocket endpoint at /ws (if HTTP and WebSocket share /, put the same Upgrade and $connection_upgrade lines inside location /).

            proxy_read_timeout 1h;
            proxy_send_timeout 1h;
            proxy_pass http://127.0.0.1:3000;
        }
    }
    Key part

    By default nginx drops the socket after 60 seconds with no frames. Raise both timeouts to an hour and keep ping/pong heartbeats every 20–30 seconds in the app.

    default:proxy_read_timeout 60sproxy_send_timeout 60s

    Setup 3: SSE streams and AI token streaming

    proxy_buffering on is the default and helps regular pages: the backend writes its response quickly into nginx’s memory and moves on to the next request while nginx trickles bytes to a slow client.

    For Server-Sent Events (Content-Type: text/event-stream), live logs, and LLM streaming, buffering gets in the way: tokens pile up inside nginx and the user stares at a blank screen until generation finishes.

    /etc/nginx/conf.d/sse.example.org.conf
    server {
        listen 80;
        server_name sse.example.org;
    
        location /sse {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";

    Shared snippet (including proxy_http_version 1.1, needed for Transfer-Encoding: chunked) plus empty Connection.

            proxy_buffering off;
            proxy_cache off;
            proxy_read_timeout 5m;
            proxy_pass http://127.0.0.1:3000;
        }
    }
    Key part

    Disables buffering and caching on this route so every data: … chunk reaches the browser as soon as the app calls flush(). Raise proxy_read_timeout to cover long model responses.

    default:proxy_buffering onproxy_read_timeout 60s

    If streaming and normal responses share the same location, you don’t need to disable buffering site-wide: return X-Accel-Buffering: no from the app on streaming responses, and nginx turns off buffering for that response alone.

    How to check

    1. Validate syntax and reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify forwarded headers and proxy_pass slash handling (using your app or a small echo server on the backend port):
      curl -s -H "Host: app.example.org" http://127.0.0.1/api/users
      # {"path": "/api/users", "http": "HTTP/1.1", "host": "app.example.org", "x_real_ip": "127.0.0.1", "proto": "http"}
      curl -s -H "Host: app.example.org" http://127.0.0.1/strip/users
      # {"path": "/users", "http": "HTTP/1.1", "host": "app.example.org", ...}
    3. Verify the WebSocket handshake — expect 101 Switching Protocols (use GET with -D - -o /dev/null, not -I, because HEAD does not upgrade WebSockets):
      curl -sD - -o /dev/null --max-time 2 --http1.1 \
        -H "Host: ws.example.org" \
        -H "Connection: Upgrade" -H "Upgrade: websocket" \
        -H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
        http://127.0.0.1/ws
      # HTTP/1.1 101 Switching Protocols
      # Connection: upgrade
      # Upgrade: websocket
    4. Verify SSE streaming with -N (disables curl’s own buffering): data: lines should appear one by one as the app flushes them, not all at once at the end:
      curl -sN -H "Host: sse.example.org" http://127.0.0.1/sse
      # data: token-1
      #
      # data: token-2
      #
      # data: token-3

    If it doesn’t work

    The backend receives /users instead of /api/users, or a double slash //users

    Cause
    proxy_pass includes a path component — even a single trailing / (proxy_pass http://127.0.0.1:3000/;) — so nginx replaced the matched location prefix with it.
    Fix
    To pass the path unchanged, omit the trailing slash: proxy_pass http://127.0.0.1:3000;. To strip the prefix cleanly, pair slashes on both: location /api/ and proxy_pass http://127.0.0.1:3000/;.

    The app builds redirects or links to http://127.0.0.1:3000 instead of https://app.example.org

    Cause
    nginx isn’t forwarding Host and X-Forwarded-Proto, or the app ignores proxy headers without an explicit setting (trust proxy in Express, --proxy-headers in Uvicorn).
    Fix
    Include snippets/proxy-headers.conf in the location block and configure the app to trust proxy headers from 127.0.0.1.

    WebSockets fail with 400 or 426, or drop after exactly 60 seconds of idle time

    Cause
    nginx talks HTTP/1.0 to backends by default and doesn’t forward Upgrade or Connection. Once upgraded, idle connections hit proxy_read_timeout (default 60s).
    Fix
    Set proxy_http_version 1.1;, proxy_set_header Upgrade $http_upgrade;, proxy_set_header Connection $connection_upgrade; (via map), and raise proxy_read_timeout to 1h.

    An SSE feed or AI chat stream stalls for tens of seconds, then dumps everything in one chunk

    Cause
    proxy_buffering is on by default, so nginx collects backend output in memory and flushes it in large blocks.
    Fix
    Add proxy_buffering off; and proxy_cache off; to the streaming location, or send X-Accel-Buffering: no from the app response.

    File uploads fail with 413 Request Entity Too Large, or slow report requests time out with 504 Gateway Timeout after one minute

    Cause
    nginx defaults client_max_body_size to 1m and proxy_read_timeout to 60s.
    Fix
    Raise both limits inside the specific route’s location (for example client_max_body_size 32m; and proxy_read_timeout 180s;) instead of loosening them server-wide.