Sub topic 2
Forwarding Host, client IP and protocol to the backend
This chapter assumes you have Nginx installed from your distribution's package, sudo access, and a web application running on a local port such as 3000. You should already know HTTP headers and status codes, and you should be comfortable editing files on the command line.
Forwarding Host, client IP and protocol
When Nginx proxies a request, the backend sees Nginx as the client. Without extra headers, the backend loses the original host name, the client's IP address and whether the visitor used HTTP or HTTPS. Use proxy_set_header to pass these values along.
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}Only trust X-Forwarded-For when the proxy sits in front of the backend. A client can send this header itself, so the backend must not treat it as proof of identity.
Grouping backends with upstream
An upstream block names a set of backend servers. proxy_pass then points to that name instead of a single address, so you can add or remove servers in one place.
Choosing a load-balancing method
Nginx uses round robin unless you choose another method inside the upstream block.
| Method | Directive | Best for |
|---|---|---|
| Round robin | none (default) | Stateless backends with similar capacity |
| Least connections | `least_conn;` | Requests with uneven durations |
| Client IP hash | `ip_hash;` | Sessions that must stay on one backend |
| Generic hash | `hash $request_uri consistent;` | Caching backends that should see the same key |
Handling failed backends with passive checks and retries
Nginx marks a server as failed after max_fails errors within fail_timeout, then skips it for that period. A backup server receives traffic only when the primary servers are unavailable. proxy_next_upstream decides which errors cause Nginx to retry another server.
upstream app_backend {
least_conn;
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.13:8080 backup;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_next_upstream error timeout http_502 http_503;
}
}Exercise
A backend at 10.0.0.11 fails three times in 30 seconds with the settings above. What happens to new requests for the next 30 seconds?
Show answer
Nginx stops sending new requests to 10.0.0.11 for 30 seconds. It sends them to the other active server, and to the backup only if no active server is available.