How to Use proxy_set_header in Nginx for Proxy Configuration
Use the
proxy_set_header directive inside an Nginx location or server block to set or override HTTP headers sent to the proxied server. This helps pass client information or control headers like Host and X-Forwarded-For when Nginx acts as a reverse proxy.Syntax
The proxy_set_header directive sets or overrides HTTP headers sent to the proxied server. It takes two arguments: the header name and the value to set.
It is used inside location, server, or http blocks.
nginx
proxy_set_header header_name header_value;
Example
This example shows how to use proxy_set_header to forward the original Host header and client IP address to the backend server.
nginx
server {
listen 80;
server_name example.com;
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;
}
}Output
When a client requests http://example.com/, Nginx forwards the request to http://backend_server with headers:
Host: example.com
X-Real-IP: <client IP>
X-Forwarded-For: <client IP plus any existing forwarded IPs>
Common Pitfalls
- Not setting
Hostheader can cause backend servers to reject or misroute requests. - Forgetting to forward client IP with
X-Real-IPorX-Forwarded-Forhides the original client IP. - Using
proxy_set_headeroutside allowed contexts causes configuration errors.
nginx
location / {
proxy_pass http://backend;
# Wrong: missing Host header
# proxy_set_header Host $host; # This line is missing
}
# Correct usage:
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}Quick Reference
| Directive | Purpose | Example 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 | Adds client IP to forwarded chain | $proxy_add_x_forwarded_for |
| proxy_set_header Connection | Controls connection header | "" (empty string to disable) |
Key Takeaways
Use proxy_set_header inside location or server blocks to modify headers sent to backend servers.
Always set the Host header to preserve the original domain name for backend processing.
Forward client IP using X-Real-IP and X-Forwarded-For headers to keep client information.
Incorrect or missing proxy_set_header directives can cause backend errors or loss of client info.
proxy_set_header syntax is: proxy_set_header header_name header_value;