Sub topic 12
Passing Host, client IP, and scheme to the app
This chapter assumes you have the Nginx and Gunicorn setup from the earlier chapters. Nginx proxies to Gunicorn over a Unix socket, and you can edit server blocks and reload Nginx. It also assumes you know basic HTTP headers.
Why the app loses information
When Nginx proxies a request, the application no longer talks to the browser. It talks to Nginx. Three facts about the original request are lost unless Nginx passes them on:
- Host: the name the client typed, such as
example.com. Nginx's default for a proxied request is the host of theproxy_passtarget, not the client's value. For a Unix socket, that islocalhost. - Client IP: the app sees the proxy's address, or no address at all on a Unix socket, instead of the visitor's.
- Scheme: Nginx may have decrypted HTTPS, but the connection to Gunicorn is plain HTTP. The app sees
http.
These cause real bugs. Redirects and generated links point to the wrong host. Rate limiting and audit logs record the proxy. Frameworks that require HTTPS for secure cookies or redirects loop forever or emit http:// links on an HTTPS site.
The fix is to have Nginx send the facts in request headers and to have the app read them, but only from a proxy it trusts.
The headers
| Header | Carries | Set by Nginx to |
|---|---|---|
| `Host` | Name the client requested | `$host` |
| `X-Real-IP` | Address of the client that connected to Nginx | `$remote_addr` |
| `X-Forwarded-For` | Chain of client and proxy addresses | `$proxy_add_x_forwarded_for` |
| `X-Forwarded-Proto` | `http` or `https` | `$scheme` |
X-Real-IP and X-Forwarded-* are conventions, not part of the core HTTP standard, so the app only honors them if you configure it to.
$host holds the host name from the request line, or the Host header, or the matching server_name, lowercased and without a port. Use $http_host instead if the app must see a non-standard port, because it keeps the header exactly as sent.
Configure Nginx
This is the location / block from the reverse proxy chapter with the headers added:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
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_add_x_forwarded_for takes any X-Forwarded-For header the client sent and appends $remote_addr to it, separated by a comma. If the client sent nothing, it is just $remote_addr.
See what the app receives
Before changing framework settings, check the raw values. This WSGI app prints what Gunicorn hands it:
def application(environ, start_response):
keys = [
"REMOTE_ADDR",
"wsgi.url_scheme",
"HTTP_HOST",
"HTTP_X_REAL_IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED_PROTO",
]
lines = [f"{k}={environ.get(k)!r}" for k in keys]
body = ("\n".join(lines) + "\n").encode()
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
])
return [body]Save it as app.py, run it under the systemd unit from the earlier chapter, reload Nginx, and send a request that includes a forged header:
sudo nginx -t && sudo systemctl reload nginx
curl -s -H "X-Forwarded-For: 1.2.3.4" http://example.com/The X-Forwarded-For value should look like 1.2.3.4, 203.0.113.9. The forged address is first and the real one, appended by Nginx, is last. X-Real-IP should hold only the real address. Over a Unix socket, REMOTE_ADDR is typically empty, because a socket peer has no IP.
Trust only what a proxy set
Anyone can send X-Forwarded-For: 1.2.3.4. The header is only reliable when it was written by a proxy you control. This leads to two rules.
- Read the right entry. Each proxy appends the address it saw. The rightmost entry was added by your own proxy, and entries further left are only as trustworthy as the proxies that wrote them. With one proxy, use
X-Real-IP, which Nginx overwrites, or the last entry ofX-Forwarded-For. Taking the first entry lets a client pick its own address. - Accept the headers only from the proxy. The app server must not be reachable directly from the internet. Bind Gunicorn to
127.0.0.1or a Unix socket, as in the earlier chapters. If a client can reach it directly, it can send these headers itself.
Teach the application to use them
Gunicorn and the scheme
Gunicorn recognizes X-Forwarded-Proto: https (also X-Forwarded-Protocol: ssl and X-Forwarded-Ssl: on) and sets wsgi.url_scheme to https. It does this only for connections from addresses listed in forwarded_allow_ips. The default is 127.0.0.1, and connections over a Unix socket are trusted. If you proxy over TCP from another host, set it explicitly:
gunicorn --workers 3 --bind 0.0.0.0:8000 \
--forwarded-allow-ips 10.0.0.5 app:applicationNever set it to * unless the port is firewalled so that only the proxy can reach it.
Flask and other WSGI apps
ProxyFix from Werkzeug rewrites REMOTE_ADDR, the host, and the scheme from the headers. The x_* arguments are the number of proxies in front of the app that you trust:
from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
@app.route("/")
def index():
return f"{request.remote_addr} {request.scheme} {request.host}\n"With x_for=1, ProxyFix takes the last entry of X-Forwarded-For. Setting it higher than your real proxy count lets clients spoof their address.
Django
Django does not trust these headers by default. Add to settings.py:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
ALLOWED_HOSTS = ["example.com"]SECURE_PROXY_SSL_HEADER makes request.is_secure() true when Nginx says https. Because Nginx already sends the real Host, you do not need USE_X_FORWARDED_HOST. Enable it only if your proxy sends the public name in X-Forwarded-Host instead.
PHP-FPM needs less
With FastCGI, Nginx is the direct peer of PHP-FPM and fills in the CGI variables itself. snippets/fastcgi-php.conf includes fastcgi.conf, which sets REMOTE_ADDR to $remote_addr and HTTPS to on when the request came in over TLS. The Host header arrives as $_SERVER['HTTP_HOST']. In a plain Nginx-to-PHP-FPM setup, $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTPS'] are therefore already correct.
When another proxy sits in front of Nginx
If Nginx itself is behind a load balancer or CDN, $remote_addr is that device's address. Use the real IP module to make Nginx replace it with the address the trusted device reports:
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;Place these in the http or server block. set_real_ip_from lists the trusted proxy addresses. With real_ip_recursive on, Nginx skips trusted addresses from the right of the header and takes the first untrusted one. After this, $remote_addr holds the visitor's address in your access log, in X-Real-IP, and in the REMOTE_ADDR that PHP sees. In this layout, $scheme still reflects the connection from the load balancer. If the load balancer terminates TLS, forward its X-Forwarded-Proto value instead, for example with a map on $http_x_forwarded_proto, and only trust it from the load balancer's addresses.
Common errors
- Every visitor appears as 127.0.0.1 or empty: the app reads
REMOTE_ADDRand no middleware or setting rewrites it from the headers. - Redirect loop to HTTPS: the framework sees
httpon every request. ForwardX-Forwarded-Protoand configure the framework to trust it. - Links point to
http://localhost: theHostheader was not forwarded, or alocationlost itsproxy_set_headerlines through the inheritance rule. - Addresses can be faked: the app trusts
X-Forwarded-Forunconditionally, or Gunicorn is reachable directly.
Exercise
A location block in your server contains proxy_pass and one line, proxy_set_header X-Request-Source nginx;. The enclosing server block defines Host, X-Real-IP, X-Forwarded-For, and X-Forwarded-Proto. The app now generates links with the wrong host. What happened, and how do you fix it?
Show answer
Because the location defines its own proxysetheader, it no longer inherits the four directives from the server block. Nginx falls back to its default Host value, which is the proxy_pass target, so the app sees the wrong host. Repeat all four header lines inside the location, or put them in a file and include that file in each location.
Exercise
A client sends X-Forwarded-For: 10.1.1.1 directly to your Nginx, which has a single proxy layer and the configuration from this chapter. What does Gunicorn receive in X-Forwarded-For and X-Real-IP if the client's real address is 203.0.113.9, and which value should the app use as the client address?
Show answer
X-Forwarded-For is 10.1.1.1, 203.0.113.9, since Nginx appends $remote_addr to the client's value. X-Real-IP is 203.0.113.9, because Nginx overwrites it. The app should use X-Real-IP or the last X-Forwarded-For entry, never the first entry, which the client controls.