Sub topic 5
Forwarding Host, client IP and protocol to the backend
This chapter assumes you can run a simple application on a local port. It also assumes you have read how Nginx configuration is organized, and that you have a working proxy_pass block. You should know what HTTP request headers are and how a TCP connection exposes a peer address.
Why the backend loses information
When Nginx proxies a request, it opens a new connection to the backend. The backend sees a TCP peer that is Nginx, not the browser. It also sees a request that Nginx rebuilt. Three facts about the original request are easy to lose:
- The host name the client asked for.
- The client's IP address.
- The protocol the client used (HTTP or HTTPS).
Applications use these facts for real work. They build absolute URLs, set Secure cookies, apply rate limits, write audit logs, and decide whether to redirect to HTTPS. If the backend gets wrong values, you see symptoms such as redirect loops, links that point to http://127.0.0.1:3000, and an access log where every client is 127.0.0.1.
The fix is to have Nginx pass the original values in request headers, and to have the backend read them.
What Nginx sends by default
Without any proxy_set_header directives, Nginx changes two headers on the way to the backend:
Hostis set to$proxy_host. That is the host and port from theproxy_passURL, for example127.0.0.1:3000.Connectionis set toclose.
Nginx also drops request header fields whose value is an empty string, and it does not forward any X-Forwarded-* header unless you configure one. The backend therefore sees Host: 127.0.0.1:3000, which is almost never what you want.
An important rule applies to inheritance. proxy_set_header directives are inherited from the enclosing level only if the current level defines none of its own. If you set one proxy_set_header inside a location, all proxy_set_header lines from the server block stop applying in that location. Put the full set in one place.
The standard header set
This is the minimal proxy from the plan, with all four headers:
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;
}
}Each line does a specific job.
| Header | Value | What the backend learns |
|---|---|---|
| `Host` | `$host` | The host name the client requested |
| `X-Real-IP` | `$remote_addr` | The address of the peer that connected to Nginx |
| `X-Forwarded-For` | `$proxy_add_x_forwarded_for` | The chain of client and proxy addresses |
| `X-Forwarded-Proto` | `$scheme` | `http` or `https`, as the client used it |
The Host header
$host holds the host name from the request line, or the Host header, or the matched server_name, in that order of preference. It is lowercase and has no port.
$http_host is the raw Host header, including any port. Use it when the backend needs the port, for example when clients reach the site on a non-standard port such as 8443. With $host, the port is lost and the backend may generate links without it.
proxy_set_header Host $http_host;The trade-off: $http_host is whatever the client sent, and it can be missing in HTTP/1.0 requests. $host always has a value. If the backend validates host names against an allow list (as many frameworks do), either variable is acceptable, but make sure the list includes what the backend will actually receive.
The client address
$remote_addr is the IP address of the directly connected peer. When Nginx is the first hop, this is the real client. X-Real-IP carries that single address.
X-Forwarded-For (XFF) is a list. $proxy_add_x_forwarded_for takes the X-Forwarded-For header from the incoming request, if there is one, and appends $remote_addr separated by a comma. If the incoming request has no such header, the value is just $remote_addr.
So a request that passed through a CDN at 203.0.113.9 from a client at 198.51.100.7 arrives at Nginx with X-Forwarded-For: 198.51.100.7, and Nginx forwards X-Forwarded-For: 198.51.100.7, 203.0.113.9. Each proxy appends the address of the peer it saw, so the leftmost entry is the one furthest from you.
The protocol
$scheme is http or https for the connection between the client and Nginx. The backend usually sees plain HTTP, so without X-Forwarded-Proto it cannot tell that the user is on HTTPS. The result is the classic redirect loop: the app sees HTTP, redirects to HTTPS, Nginx forwards that request over plain HTTP again, and the cycle repeats.
Seeing what the backend receives
Do not guess. Run a tiny backend that echoes the headers it gets. This Python script needs only the standard library:
from http.server import BaseHTTPRequestHandler, HTTPServer
class Echo(BaseHTTPRequestHandler):
def do_GET(self):
lines = [f"peer={self.client_address[0]}"]
lines += [f"{k}: {v}" for k, v in self.headers.items()]
body = "\n".join(lines).encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 3000), Echo).serve_forever()Save it as echo.py, start it with python3 echo.py, then test the proxy from another terminal:
sudo nginx -t && sudo systemctl reload nginx
curl -s -H "X-Forwarded-For: 198.51.100.7" http://example.com/If example.com does not resolve on your machine, add --resolve example.com:80:127.0.0.1 to the curl command. You should see peer=127.0.0.1, Host: example.com, and an X-Forwarded-For value that ends with the address Nginx saw as the client.
Do not trust a client-supplied X-Forwarded-For
Look at the test above: you supplied your own X-Forwarded-For, and Nginx kept it and appended to it. This is correct behavior for a proxy in a chain, but it creates a security problem when Nginx is the edge. A client can claim any address, and the leftmost entry in XFF is then fake.
Two rules keep this safe:
- If Nginx is directly exposed to clients, do not forward what they send. Set the header to
$remote_addronly:
proxy_set_header X-Forwarded-For $remote_addr;- If Nginx sits behind a load balancer or CDN you control, the backend (or Nginx itself) should walk the XFF list from the right and stop at the first address that is not a trusted proxy.
Nginx can do the second job itself with the realip module. It rewrites $remote_addr so that logs, allow/deny rules and limit_req all use the real client:
set_real_ip_from 203.0.113.0/24;
real_ip_header X-Forwarded-For;
real_ip_recursive on;set_real_ip_from lists the trusted proxies. With real_ip_recursive on, Nginx skips trusted addresses from the right of the header and takes the first untrusted one. Most distribution packages build Nginx with this module. Check with nginx -V 2>&1 | grep realip.
The forwarded headers in a standard form
X-Forwarded-* headers are a convention, not a standard. RFC 7239 defines a single Forwarded header that carries the same data:
Forwarded: for=198.51.100.7;proto=https;host=example.comFew applications read it by default, so most deployments still send X-Forwarded-*. Pick whichever your backend framework reads, and do not send conflicting values in both forms.
Telling the backend to trust the headers
Sending headers is half the job. The backend must be configured to read them, and it should only do so for requests that come from Nginx. Each stack names this differently: Express has trust proxy, Django has SECURE_PROXY_SSL_HEADER, Rails has config.action_dispatch.trusted_proxies, and Gunicorn has forwarded_allow_ips. If the backend trusts these headers from any peer, a client that can reach it directly can forge them. Bind the backend to 127.0.0.1 or a private network, or block outside access with a firewall.
Overriding values with map
Sometimes Nginx itself is behind another proxy that terminates TLS, so $scheme is always http at Nginx. In that case, pass along the value the first proxy reported, if it is valid, and fall back to $scheme:
map $http_x_forwarded_proto $forwarded_proto {
default $scheme;
https https;
http http;
}A map block lives in the http context, outside any server. Then use the result in the location:
proxy_set_header X-Forwarded-Proto $forwarded_proto;Because the map accepts only the two valid values, a client cannot inject arbitrary text. Only use this form when the upstream proxy is trusted. At an exposed edge, use plain $scheme.
Hiding and adding headers
Two related directives are worth knowing:
proxy_set_header Name "";stops Nginx from sending a header to the backend. Use it to remove a header that clients should not control.proxy_hide_headerandproxy_pass_headerwork in the other direction. They control which response headers from the backend reach the client.
A related problem is redirects generated by the backend. If the backend sends Location: http://127.0.0.1:3000/login, the browser cannot follow it. The best fix is the headers in this chapter, because a backend that knows the real Host and scheme builds correct URLs. The legacy fix is proxy_redirect, which rewrites Location headers in responses. Its default is already default, which rewrites a redirect that starts with the proxy_pass URL to the current $host. If your backend redirects to another form, set the rule explicitly:
proxy_redirect http://127.0.0.1:3000/ /;Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Backend logs show only `127.0.0.1` | The app ignores `X-Forwarded-For` | Enable trusted-proxy support in the app |
| Redirect loop between HTTP and HTTPS | Backend never sees `X-Forwarded-Proto` | Send the header and make the app read it |
| Links point to `127.0.0.1:3000` | `Host` is the default `$proxy_host` | Add `proxy_set_header Host $host;` |
| Headers vanish in one location | A local `proxy_set_header` hid the inherited ones | Repeat all headers at that level, or define them once |
| Wrong port in generated links | `$host` drops the port | Use `$http_host` |
| Every client appears to share one address | Another proxy sits in front and `realip` is not set | Configure `set_real_ip_from` for that proxy |
| Virtual host on the backend returns the default site | Backend routes by `Host` and got the wrong one | Forward `$host` |
Putting shared headers in one file
When you have many locations, repeating the four lines invites the inheritance mistake. Put them in a snippet and include it. The path below is a common convention, not a requirement:
# /etc/nginx/snippets/proxy-headers.conf
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;location / {
include snippets/proxy-headers.conf;
proxy_pass http://127.0.0.1:3000;
}If a location needs an extra header, add it after the include in the same block. Both the included lines and the new line then apply, because they are at the same level.
Verifying the whole chain
Check the result in this order:
- Run
sudo nginx -tto validate the syntax. - Reload with
sudo systemctl reload nginx. - Send a request with
curland compare the echo output with what you expect. - Repeat with a forged
X-Forwarded-For, and confirm your policy (append, overwrite, or trust only known proxies) does what you intended. - Check the backend's own access log to see whether it records the real client address.
Exercise
Your app sits behind Nginx on the same host. Users report that after logging in over HTTPS, the browser keeps bouncing between the https:// and http:// versions of the login URL. The Nginx location has proxy_set_header Host $host; only. What is the cause, and what two changes fix it?
Show answer
The app sees plain HTTP from Nginx, so it redirects to HTTPS. The next request again reaches the app over plain HTTP, so it redirects again. Nginx does not tell the app the original protocol. Fix it by adding proxy_set_header X-Forwarded-Proto $scheme; in Nginx, and by configuring the app to trust that header from the proxy (for example Express trust proxy or Django SECURE_PROXY_SSL_HEADER).
Exercise
Nginx is exposed directly to the internet. A scanner sends X-Forwarded-For: 10.0.0.5, and your app's admin area allows 10.0.0.0/8. Which Nginx setting prevents the bypass, and why?
Show answer
Use proxy_set_header X-Forwarded-For $remote_addr;. This discards the client-supplied list and sends only the address Nginx actually saw. With $proxy_add_x_forwarded_for, the forged value stays at the left of the list and the app may trust it.