patternjavascriptMajor
Nginx reverse proxy to Node.js app with correct headers
Viewed 0 times
nginxreverse proxyX-Forwarded-Fortrust proxyreal IPproxy headers
Problem
When proxying requests from nginx to a Node.js backend, the app sees 127.0.0.1 as the client IP and incorrect protocol/host headers, breaking features that depend on real client information.
Solution
Set proxy headers explicitly in the nginx location block:
In Express, trust the proxy:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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_cache_bypass $http_upgrade;
}
}In Express, trust the proxy:
app.set('trust proxy', 1);
// Now req.ip returns the real client IPWhy
Nginx rewrites headers when proxying. Without these headers, the backend cannot determine the real client IP or whether the original request was HTTPS.
Gotchas
- proxy_http_version 1.1 is required for WebSocket upgrades to work
- 'trust proxy' in Express must match your exact proxy chain depth — use a number like 1, not just true, in production
- X-Forwarded-For is a comma-separated list if multiple proxies are in the chain
Revisions (0)
No revisions yet.