An Nginx reverse proxy receives client requests and forwards them to one or more internal servers (Node.js, Python, Java, a container), then returns the response as if it had produced it itself. You configure it with a server block and the proxy_pass directive, for example location / { proxy_pass http://127.0.0.1:3000; }, plus the headers the backend needs to know who the real client is.
I tested every configuration in this guide in October 2026 with nginx 1.30.6, the current stable release, in a Docker Compose lab with two test backends. The outputs are real, shortened where needed. Some behaviours are not what you’d expect: load balancing that sends everything to the same server, a dead backend that costs the first user 60 seconds, an nginx -t that fails because a container is stopped.
Nginx reverse proxy in 60 seconds
upstream app {
zone app 64k; # state shared between workers
server 10.0.0.11:3000 max_fails=2 fail_timeout=10s;
server 10.0.0.12:3000 max_fails=2 fail_timeout=10s;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://app;
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;
proxy_connect_timeout 3s; # default 60s
}
}
sudo nginx -t # check the syntax (and resolve upstream names)
sudo systemctl reload nginx # apply without dropping connections
sudo tail -f /var/log/nginx/error.log
With a single backend you can write proxy_pass http://10.0.0.11:3000; directly and skip the upstream block. The rest of the guide explains why each line is there.
Which nginx version you’re running (and why it matters)
The current stable branch is 1.30.x, mainline is 1.31.x (source: nginx.org/en/download.html). Distributions ship much older ones. In the official containers, as of October 2026:
| Source | Version | What changes for the reverse proxy |
|---|---|---|
Debian 12, apt install nginx |
1.22.1 | needs listen 443 ssl http2; no upstream keepalive by default |
Ubuntu 24.04, apt install nginx |
1.24.0 | same as above |
Debian 13, apt install nginx |
1.26.3 | has the http2 on; directive; no resolve in upstreams |
nginx.org repository / nginx:stable image |
1.30.6 | resolve in upstreams, keepalive and HTTP/1.1 to the backend on by default |
Three recent changes affect the configurations you find online:
- since 1.25.1, HTTP/2 is enabled with the
http2 on;directive, no longer with alistenparameter (HTTP/2 module documentation); - since 1.27.3, the
resolveparameter for upstream servers, previously reserved for the commercial version, is available in the open source version; - since 1.29.7, nginx speaks HTTP/1.1 to the backend and keeps up to 32 idle connections open per worker with no configuration. Before that you needed
proxy_http_version 1.1;,proxy_set_header Connection "";andkeepalivein the upstream block (keepalive documentation).
If you’re on Ubuntu 24.04 or Debian 12 with the distribution package, you still need those two keepalive lines. On 1.30 they do no harm, so I keep them in the examples.
The test lab
To try everything without touching a server I used three containers: nginx in front and two instances of traefik/whoami, a tiny HTTP server that replies by printing its own name and the headers it received. It’s the quickest way to see what actually reaches the backend.
services:
be1:
image: traefik/whoami
command: --name be1
be2:
image: traefik/whoami
command: --name be2
proxy:
image: nginx:stable
ports: ["127.0.0.1:18080:80", "127.0.0.1:18443:443"]
volumes:
- ./conf:/etc/nginx/conf.d:ro
- ./certs:/etc/nginx/certs:ro
depends_on: [be1, be2]
$ docker compose up -d
$ docker compose exec proxy nginx -v
nginx version: nginx/1.30.6
On a real server, installing from the official repository is described at nginx.org/en/linux_packages.html; with the distribution package, sudo apt install nginx is enough. Either way, a site’s configuration goes in /etc/nginx/conf.d/name.conf (or in sites-available with a link in sites-enabled on Debian/Ubuntu packages).
proxy_pass and the trailing slash trap
The rule behind most 404s behind a reverse proxy: if proxy_pass contains a URI (even just /), nginx replaces the part of the path that matched the location with that URI. If it doesn’t, the original path is passed through unchanged. Two almost identical locations (the names mean “with slash” and “without slash”):
location /con-slash/ { proxy_pass http://be1:80/; }
location /senza-slash/ { proxy_pass http://be1:80; }
What the backend receives for the same /api/users request:
$ curl -s http://app.example.test/con-slash/api/users | grep GET
GET /api/users HTTP/1.1
$ curl -s http://app.example.test/senza-slash/api/users | grep GET
GET /senza-slash/api/users HTTP/1.1
With the slash the /con-slash/ prefix disappears; without it the path arrives in full. Neither is wrong: the first is for applications that don’t know they are published under a subpath, the second for applications that do (for example an app configured with a /senza-slash base path). The typical case to avoid is location /app (no slash) with proxy_pass http://backend/;: a request for /applicazione still matches the location, and in the lab it arrived like this:
$ curl -s http://app.example.test/applicazione | grep GET # location /app + proxy_pass http://be1:80/
GET /licazione HTTP/1.1
Always keep the trailing slash consistent between location and proxy_pass.
A related second trap: inside a regular-expression location a URI in proxy_pass is not allowed, and nginx -t says so clearly:
$ sudo nginx -t # with: location ~ ^/api/ { proxy_pass http://127.0.0.1:8080/; }
nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /etc/nginx/conf.d/default.conf:3
nginx: configuration file /etc/nginx/nginx.conf test failed
In that case you remove the URI from proxy_pass and, if the path needs rewriting, use rewrite ^/api/(.*)$ /$1 break; before proxy_pass. The behaviour is described in the proxy_pass documentation.
Headers: Host, X-Real-IP, X-Forwarded-For, X-Forwarded-Proto
Without proxy_set_header, nginx sends the backend the name written in proxy_pass as the Host (the $proxy_host variable), and no information about the client. In the lab, from a location with no headers set:
$ curl -s http://app.example.test/con-slash/ | grep -E "^(Host:|X-)"
Host: be1
The backend thinks it’s called be1: it generates links and redirects to a name that doesn’t exist outside, and a name-based virtual host doesn’t answer. With the four headers set, and a client that sends a fake X-Forwarded-For of its own:
$ curl -s -H 'X-Forwarded-For: 203.0.113.50' http://app.example.test/
Name: be1
RemoteAddr: 192.168.48.4:51004
GET / HTTP/1.1
Host: app.example.test
X-Forwarded-For: 203.0.113.50, 192.168.48.1
X-Forwarded-Proto: http
X-Real-Ip: 192.168.48.1
Three things to read in this output:
RemoteAddris nginx’s IP, not the client’s: without headers the backend always logs the same address;X-Real-IPholds the address that connected to nginx ($remote_addr), which the client can’t forge;X-Forwarded-Forwith$proxy_add_x_forwarded_forappends the real IP to whatever the client sent. The first value,203.0.113.50, I typed by hand. An application that takes the first element of the list for rate limiting or an allowlist can be fooled by a header.
Rule of thumb: if nginx is the first point of contact with the Internet, have the backend read X-Real-IP or the last element of X-Forwarded-For. If there’s another proxy or a CDN in front of nginx, nginx must first recover the real IP with the realip module (set_real_ip_from with the trusted proxy’s addresses and real_ip_header X-Forwarded-For;), otherwise $remote_addr is the CDN’s IP.
X-Forwarded-Proto prevents the classic redirect loop: the application receives plain HTTP from nginx, thinks the client isn’t on HTTPS and sends it to https://, forever. With the header and a framework configured to trust the proxy, the problem goes away.
WebSocket: Upgrade and Connection
A WebSocket connection starts as an HTTP request with Upgrade: websocket and Connection: Upgrade. These are hop-by-hop headers: nginx doesn’t forward them on its own, you have to say so explicitly. The recommended form uses a map in the http context, so normal requests don’t get a spurious Connection: upgrade:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
...
location /echo {
proxy_pass http://be1:80;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 1h;
}
}
The same handshake request, to this location and to a location without the two headers:
$ curl -si -H "Connection: Upgrade" -H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
http://app.example.test/echo
HTTP/1.1 101 Switching Protocols
Server: nginx/1.30.6
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
$ curl -si ... http://app.example.test/con-slash/echo # location without Upgrade/Connection
HTTP/1.1 400 Bad Request
Server: nginx/1.30.6
...
Bad Request
With the Python websockets client, messages flow through nginx (the test client printed in Italian, “ricevuto” = “received”):
ricevuto: ciao dal client
ricevuto: secondo messaggio
proxy_read_timeout 1h is not a detail: on an idle WebSocket nginx closes the connection after the read timeout, 60 seconds by default. Either raise the timeout or have the application send a periodic ping more often than that.
Timeouts and buffering
The three proxy timeouts default to 60 seconds (ngx_http_proxy_module):
| Directive | Default | What it measures | When it expires |
|---|---|---|---|
proxy_connect_timeout |
60s | opening the TCP connection to the backend | tries the next server, then 504 |
proxy_read_timeout |
60s | wait between two reads from the backend (not the total duration) | 504 |
proxy_send_timeout |
60s | wait between two writes to the backend | 504 |
In the lab, a location with proxy_read_timeout 3s and a backend that replies after 5 or 2 seconds (whoami accepts a ?wait= parameter):
$ curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" "http://app.example.test/lento/?wait=5s"
504 3.003630s
$ curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" "http://app.example.test/lento/?wait=2s"
200 2.006447s
The connect timeout should almost always be lowered: on a local network a healthy backend accepts the connection in milliseconds, and 60 seconds of waiting only means making the user wait before another server is tried. See the failover section for the numbers. The read timeout, on the other hand, should only be raised where needed (a slow export, a report), in a dedicated location, not for the whole site.
Buffering (proxy_buffering on, the default) makes nginx read the backend’s response as fast as possible, freeing it up, and then deliver it to the client at the client’s pace. With slow mobile clients that’s an advantage. Turn it off (proxy_buffering off;) for streaming responses such as Server-Sent Events or progressive output, otherwise the client gets everything in one block at the end. Alternatively, the backend can send the X-Accel-Buffering: no header on streaming responses only. For large uploads also check client_max_body_size: the 1 MB default produces a 413 Request Entity Too Large generated by nginx, not by the application.
Upstreams and load balancing: the worker problem
With several backends you define an upstream group and use it in proxy_pass. The default method is round-robin. The first configuration I tried was the one you find everywhere:
upstream app {
server be1:80 max_fails=2 fail_timeout=10s;
server be2:80 max_fails=2 fail_timeout=10s;
}
And the result, six requests over six separate connections:
$ for i in $(seq 6); do curl -s http://app.example.test/ | grep '^Name'; done
Name: be1
Name: be1
Name: be1
Name: be1
Name: be1
Name: be1
No balancing at all. The reason: each nginx worker keeps its own round-robin state, and with worker_processes auto on a 32-core machine there are 32 workers. Each new connection lands on a different worker, which starts from the first server in the list. On the same keepalive connection, in fact, the alternation is there (be1, be2, be1, be2). The fix is the zone directive, which puts the group’s configuration and state in memory shared between workers:
upstream app {
zone app 64k;
server be1:80 max_fails=2 fail_timeout=10s;
server be2:80 max_fails=2 fail_timeout=10s;
}
$ for i in $(seq 6); do curl -s http://app.example.test/ | grep '^Name'; done
Name: be1
Name: be2
Name: be1
Name: be2
Name: be1
Name: be2
With real traffic and many clients the imbalance without zone is less extreme, but it’s still there, and the same goes for failure counting, because max_fails is also counted per worker. With zone, a backend that one worker marks as failed is failed for all of them.
The other methods are enabled with one line in the upstream block: least_conn; (server with the fewest active connections), ip_hash; (same client to the same server, useful for non-shared sessions), hash $request_uri consistent;. Weight is set per server: server 10.0.0.11:3000 weight=3;. A spare server used only when the others are down is marked with backup.
What happens when a backend goes down
max_fails=2 fail_timeout=10s means: after 2 failed attempts within 10 seconds, the server is considered unavailable for 10 seconds. The defaults are max_fails=1 and fail_timeout=10s. What counts as a failure is decided by proxy_next_upstream, which defaults to error timeout: a connection error or a timeout, not the application’s 500 responses.
I stopped be2 with docker compose stop be2 and sent requests one at a time, with the default timeouts:
15:16:00 200 0.002405s Name: be1
15:16:00 200 60.004528s Name: be1
15:17:00 200 0.002152s Name: be1
15:17:00 200 18.549446s Name: be1
15:17:19 200 0.003497s Name: be1
15:17:19 200 0.001991s Name: be1
The client always gets a 200, because nginx retries the request on the other server, but the second request took 60 seconds: the proxy_connect_timeout towards an address that no longer answers. A host that is powered off, unlike a stopped service on a running host, doesn’t refuse the connection: it just stays silent. The same test with proxy_connect_timeout 2s:
15:18:20 200 0.003375s Name: be1
15:18:20 200 2.005300s Name: be1
15:18:22 200 0.002470s Name: be1
15:18:22 200 2.007668s Name: be1
15:18:24 200 0.004204s Name: be1
15:18:24 200 0.002328s Name: be1
# wait 11 s (fail_timeout=10s)
15:18:35 200 0.002168s Name: be1
15:18:36 200 2.003711s Name: be1
15:18:38 200 0.001982s Name: be1
Two slow requests (max_fails=2), then 10 seconds in which nginx no longer tries be2, then a new attempt as soon as fail_timeout expires. In the access log, with a format that includes the upstream variables, you can see the double attempt:
log_format upstreamlog '$remote_addr "$request" $status '
'upstream=$upstream_addr ustatus=$upstream_status '
'rt=$request_time urt=$upstream_response_time';
access_log /var/log/nginx/upstream.log upstreamlog;
192.168.48.1 "GET / HTTP/1.1" 200 upstream=192.168.48.2:80 ustatus=200 rt=0.001 urt=0.001
192.168.48.1 "GET / HTTP/1.1" 200 upstream=192.168.48.3:80, 192.168.48.2:80 ustatus=504, 200 rt=2.004 urt=2.002, 0.002
The 504 in the ustatus column never reached the client: it’s the failed attempt to be2, followed by the 200 from be1. This log format is the first thing to enable when a reverse proxy is “slow every now and then”. And in error.log:
[error] upstream timed out (110: Connection timed out) while connecting to upstream, ... upstream: "http://192.168.48.3:80/"
[warn] upstream server temporarily disabled while connecting to upstream, ... upstream: "http://192.168.48.3:80/"
Watch out for POST requests: since 1.9.13 nginx doesn’t retry them on another server if the request has already been sent to the first one, so as not to run an operation twice. A backend that dies halfway through a POST produces an error for that client, and that is the correct behaviour.
nginx -t and upstream names that don’t resolve
With be2 stopped I tried to reload a modified configuration:
$ sudo nginx -t
nginx: [emerg] host not found in upstream "be2:80" in /etc/nginx/conf.d/default.conf:3
nginx: configuration file /etc/nginx/nginx.conf test failed
nginx resolves the names of upstream servers when the configuration is loaded. If a name doesn’t resolve, the whole configuration is invalid: the reload is refused (the old one stays active) and a cold start fails. With Docker Compose this happens every time a container is stopped, because its name disappears from the internal DNS; on a server it happens when a DNS record is deleted or the resolver doesn’t answer at startup. An extra risk: the address resolved at startup stays in memory, so if the backend changes IP nginx keeps looking for it at the old address.
Since 1.27.3 the open source version supports the resolve parameter, which requires a zone and a resolver (documentation):
resolver 127.0.0.11 valid=10s; # Docker's internal DNS; on a server, your own resolver
upstream app {
zone app 64k;
server backend-inesistente:80 resolve;
}
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
With resolve, nginx starts even if the name doesn’t exist yet and updates the addresses while it runs. The distribution versions (1.22, 1.24, 1.26) don’t have the parameter: there you use IP addresses in the upstream, or accept that the reload may fail and check for it.
A habit worth building: sudo nginx -t && sudo systemctl reload nginx, always together. As shown above, a reload with an invalid configuration keeps the old one active; a restart, instead, stops nginx and fails to start it again, and the site stays down.
502 and 504: how to read them in error.log
The code the client sees tells you little; the error.log line tells you exactly what happened. These are the ones I got in the lab, triggering the errors one by one:
| Line in error.log | Code to the client | Cause | What to check |
|---|---|---|---|
connect() failed (111: Connection refused) while connecting to upstream |
502 | host up, no process on the port | is the service running? is it listening on that port and that interface (127.0.0.1 or 0.0.0.0)? |
connect() failed (113: No route to host) |
502 | host unreachable | correct IP, host powered on, firewall |
upstream timed out (110: Connection timed out) while connecting to upstream |
504 | no reply to the SYN within proxy_connect_timeout |
host powered off, firewall dropping packets |
upstream timed out (110: Connection timed out) while reading response header from upstream |
504 | connection open, the application doesn’t answer within proxy_read_timeout |
slow queries, application workers saturated |
no live upstreams while connecting to upstream |
502 | every server in the group marked unavailable | the previous line says why they went down |
The “all down” case in the lab, with both backends stopped: first a 504 after 4 seconds (two 2-second attempts), then immediate 502s for the 10 seconds of fail_timeout:
504 4.005595s
502 2.006566s
502 0.003514s
502 0.001020s
[error] no live upstreams while connecting to upstream, ... upstream: "http://app/"
Two causes of 502 that don’t show up in the lab but do on real servers. With SELinux enabled (RHEL, Rocky, Alma), nginx can’t open network connections to backend ports until you enable setsebool -P httpd_can_network_connect 1: in error.log you’ll find (13: Permission denied) while connecting to upstream. And with a backend on a Unix socket, the file must be readable and writable by the user the workers run as (www-data or nginx).
HTTPS: test certificate, http2 on and Let’s Encrypt
For the lab a self-signed certificate is enough:
openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj "/CN=app.example.test" \
-addext "subjectAltName=DNS:app.example.test" -keyout app.key -out app.crt
server {
listen 443 ssl;
http2 on;
server_name app.example.test;
ssl_certificate /etc/nginx/certs/app.crt;
ssl_certificate_key /etc/nginx/certs/app.key;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
proxy_pass http://app;
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;
}
}
$ curl -sk --http2 -o /dev/null -w "%{http_version} %{http_code}\n" https://app.example.test/
2 200
$ curl -sk https://app.example.test/ | grep -E "^X-Forwarded-Proto|^GET"
GET / HTTP/1.1
X-Forwarded-Proto: https
$ curl -s https://app.example.test/ ; echo "exit=$?" # without -k
exit=60
$ curl -s --cacert app.crt -o /dev/null -w "%{http_code}\n" https://app.example.test/
200
The client speaks HTTP/2 to nginx, but the backend receives HTTP/1.1: these are two separate connections, and HTTP/2 towards the client requires nothing from the application. curl’s exit code 60 is the unverifiable certificate, expected with a self-signed one. openssl s_client -alpn h2 confirms the negotiation: ALPN protocol: h2.
The old syntax, listen 443 ssl http2;, still works on recent versions, but nginx -t flags it:
nginx: [warn] the "listen ... http2" directive is deprecated, use the "http2" directive instead in /etc/nginx/conf.d/default.conf:2
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
On Debian 12 and Ubuntu 24.04 (1.22 and 1.24), on the other hand, http2 on; doesn’t exist and you have to use the listen form. If you copy a configuration between servers running different versions, this is the first thing to check.
In production you get the certificate from Let’s Encrypt with certbot, following the instructions for your system at certbot.eff.org. The nginx plugin edits the server block and adds the SSL directives:
sudo certbot --nginx -d app.example.com
sudo certbot renew --dry-run # check that automatic renewal works
I didn’t run these two commands in the lab, because Let’s Encrypt has to reach the domain from the Internet on port 80 (HTTP-01 challenge). Two practical notes: the server block on port 80 must stay reachable even after the redirect to HTTPS, because renewals go through it; and after certbot has edited the files, reread the server block and run nginx -t, so you know exactly what was added.
Caching with proxy_cache
nginx’s cache stores backend responses on disk and serves them without contacting the backend. The zone is defined in the http context and enabled in the location:
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app_cache:10m
max_size=100m inactive=10m use_temp_path=off;
server {
...
location /cache/ {
proxy_pass http://app/;
proxy_cache app_cache;
proxy_cache_valid 200 1m;
proxy_cache_use_stale error timeout updating http_502 http_503;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status always;
}
}
$ for i in 1 2 3; do curl -s -D - -o /dev/null http://app.example.test/cache/ | grep -i x-cache; done
X-Cache-Status: MISS
X-Cache-Status: HIT
X-Cache-Status: HIT
The most valuable line is proxy_cache_use_stale. I set the validity to 10 seconds, made one request, waited 11 seconds and stopped both backends:
X-Cache-Status: MISS
# after 11 s, backends stopped
HTTP/1.1 200 OK
X-Cache-Status: STALE
The expired content is served anyway instead of a 502. A page never requested before, with the backends down, returns a 502 instead: the cache only protects what it already has.
Things to know before enabling it: nginx doesn’t cache responses with Set-Cookie or with Cache-Control: private/no-store, and by default only stores GET and HEAD. On per-user pages (members’ area, shopping cart) don’t enable it blindly: exclude them with proxy_cache_bypass and proxy_no_cache based on the session cookie. proxy_cache_lock on ensures that, when an entry expires, only one request goes to the backend while the others wait.
Rate limiting, briefly
The per-IP request limit is defined in http and applied to the location you want to protect:
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://app;
}
Without limit_req_status the returned code is 503, which is easy to confuse with a broken backend. If nginx is behind a CDN, the $binary_remote_addr key only works once realip is configured; otherwise you’re limiting the CDN’s IP and blocking everyone at once. Security headers and more detailed limits are covered in the guide to a secure Nginx reverse proxy with HTTPS, headers and rate limiting.
Summary: directives and starting values
| Directive | Suggested value | Why |
|---|---|---|
proxy_pass |
trailing slash consistent with the location |
with a URI it replaces the prefix, without one it passes it in full |
proxy_set_header Host |
$host |
the default is the upstream name |
X-Real-IP / X-Forwarded-For |
$remote_addr / $proxy_add_x_forwarded_for |
the first XFF element is written by the client |
X-Forwarded-Proto |
$scheme |
prevents HTTPS redirect loops |
zone (upstream) |
64k |
without it, round-robin and max_fails are per worker |
proxy_connect_timeout |
2-5s on a LAN | the 60s default lands on the first user when a host goes down |
proxy_read_timeout |
60s, higher only where needed | 504 “while reading response header” |
max_fails / fail_timeout |
2 / 10s | how quickly a server is taken out of rotation |
http2 |
http2 on; (since 1.25.1) |
listen ... http2 is deprecated |
proxy_cache_use_stale |
error timeout updating http_502 http_503 |
serves the expired copy if the backend is down |
When nginx alone isn’t enough (active health checks, real-time backend statistics, TCP balancing with richer logic), the next step is a dedicated load balancer like the one described in the guide to HAProxy for load balancing and high availability. And if nginx’s logs grow out of control, rotation is handled with logrotate.
Frequently Asked Questions
Why does nginx return 502 Bad Gateway?
Because it couldn’t get a valid response from the backend. The matching line in /var/log/nginx/error.log tells you why: Connection refused means no process is listening on the port, No route to host means the host is unreachable, no live upstreams means every server in the group was excluded after earlier errors, and Permission denied means SELinux or the permissions on a socket are blocking the connection.
What is the difference between 502 and 504 in a reverse proxy?
A 502 means the connection to the backend failed or the response was invalid, usually right away. A 504 means the backend didn’t answer in time: either it didn’t accept the connection within proxy_connect_timeout, or it didn’t send the response within proxy_read_timeout. The error.log tells the two cases apart with while connecting and while reading response header.
Why does nginx send every request to the same backend?
Usually because the zone directive is missing from the upstream block. Without shared memory each worker has its own round-robin counter and starts from the first server, so with many workers and short connections the first server gets almost everything. Adding zone with 64k of memory restores the alternation. ip_hash and hash also concentrate traffic, but by design.
Do I still need proxy_http_version 1.1 for WebSocket and keepalive?
Since version 1.29.7, HTTP/1.1 to the backend and keepalive are on by default, but distribution versions such as those in Debian 12, Ubuntu 24.04 and Debian 13 are older and still need it. WebSocket also always needs the Upgrade and Connection headers, which nginx doesn’t forward on its own, and a proxy_read_timeout suited to long-lived connections.
How do I enable HTTP/2 on nginx?
Since version 1.25.1 you write http2 on inside the server block, next to listen 443 ssl. The old form listen 443 ssl http2 still works, but nginx -t flags it as deprecated. On versions before 1.25.1, such as those in Debian 12 and Ubuntu 24.04, the listen form is the only valid one.
Read also
Read also: SSH Hardening Linux: Complete Guide 2026 (10 Critical Settings)
Read also: Fail2ban on Linux: Complete Setup and SSH Hardening
Read also: UFW Firewall Ubuntu: Complete Configuration from A to Z (2026)