← All articles and news

Web & network

Nginx reverse proxy for HTTP and WebSocket

Test the origin, forward the required headers and diagnose 502 responses. DNS and host routing are separate steps.

MerMiko2 min read

Test the application first

A proxy does not start the application for you. Before editing Nginx, verify the application at its internal address, for example curl -I http://127.0.0.1:3000/. If the proxy runs in a different container, its 127.0.0.1 refers to that container, not to the host or another service.

Configure the correct host and location

Place this fragment in the relevant host’s server block. It explicitly uses HTTP/1.1 for compatibility with older Nginx installations. This does not require exposing the application port to the Internet.

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

location /socket/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

Match /socket/ to the application’s endpoint. A trailing slash in proxy_pass can change URI forwarding, so do not add one without checking the intended behavior.

Validate before reloading

sudo nginx -t
# Reload only after validation succeeds:
sudo systemctl reload nginx

Check both an ordinary HTTP response and a WebSocket connection. Long-lived connections may require application heartbeats and suitable timeouts. A 200 response from the home page does not establish that the WebSocket endpoint works.

Diagnose one layer at a time

  • A proxy-generated 404 calls for checking the hostname route, not just DNS.
  • For 502, check the upstream address, port, process and container network.
  • For TLS failures, compare certificate names and the origin connection mode.
  • The application should trust forwarded headers only from known proxies; an arbitrary X-Forwarded-For value is not a verified client identity.

Sources and documentation

Source links are retained for checking dates, availability and original context.

Continue reading

Guide library Latest news