0
0
NginxHow-ToBeginner · 3 min read

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 header HEADER_NAME to HEADER_VALUE.
  • HEADER_VALUE can be a static string or a variable like $host or $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 Host header, 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

DirectivePurposeTypical Value
proxy_set_header HostSets the Host header sent to backend$host
proxy_set_header X-Real-IPSends client IP to backend$remote_addr
proxy_set_header X-Forwarded-ForAppends client IP chain$proxy_add_x_forwarded_for
proxy_set_header X-Forwarded-ProtoSends 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.