How to Set Proxy Headers in Nginx for Reverse Proxy
To set proxy headers in
nginx, use the proxy_set_header directive inside a location or server block. This lets you forward or modify headers like Host, X-Real-IP, and X-Forwarded-For when proxying requests.Syntax
The proxy_set_header directive sets or overrides HTTP headers sent to the proxied server. It is used inside location, server, or http blocks.
proxy_set_header HEADER_NAME HEADER_VALUE;sets the headerHEADER_NAMEtoHEADER_VALUE.HEADER_VALUEcan be a static string or a variable like$hostor$remote_addr.
nginx
proxy_set_header HEADER_NAME HEADER_VALUE;
Example
This example shows how to set common proxy headers to forward the original client IP and host to the backend server.
nginx
server {
listen 80;
location / {
proxy_pass http://backend_server;
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;
}
}Common Pitfalls
Common mistakes when setting proxy headers include:
- Not setting
Hostheader, which can cause backend servers to reject requests or serve wrong content. - Forgetting to append client IP to
X-Forwarded-For, losing the original client IP. - Setting headers outside the correct block, so they don't apply to proxied requests.
Example of wrong and right usage:
nginx
# Wrong: Missing proxy_set_header directives
location / {
proxy_pass http://backend_server;
}
# Right: Proper proxy headers set
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}Quick Reference
| Directive | Purpose | Typical Value |
|---|---|---|
| proxy_set_header Host | Sets the Host header sent to backend | $host |
| proxy_set_header X-Real-IP | Sends client IP to backend | $remote_addr |
| proxy_set_header X-Forwarded-For | Appends client IP chain | $proxy_add_x_forwarded_for |
| proxy_set_header X-Forwarded-Proto | Sends original protocol (http/https) | $scheme |
Key Takeaways
Use proxy_set_header inside location or server blocks to set headers for proxied requests.
Always set Host, X-Real-IP, and X-Forwarded-For headers to forward client info correctly.
Use $proxy_add_x_forwarded_for to append client IP instead of overwriting it.
Place proxy_set_header directives in the same block as proxy_pass for them to apply.
Incorrect or missing headers can cause backend servers to misbehave or lose client info.