8

What can I use in the nginx config to make it clear any existing X-Forwarded-For headers before setting its own? I am currently using Nginx to terminate SSL before passing traffic to HAProxy to load balance.

Right now, I have:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

This will append a new IP address to the end of any existing X-Forwarded-For IP addresses however. Is there a way to only keep the address seen by Nginx?

sidprak
  • 400
  • 4
  • 9

2 Answers2

9

Just don't use $proxy_add_x_forwarded_for - the whole purpose that it exists is to do the appending behavior.

Instead:

proxy_set_header X-Forwarded-For $remote_addr;
Shane Madden
  • 112,982
  • 12
  • 174
  • 248
  • The point of the `X-Forwarded-For` header is to contain the IP of the original client, plus the IP of the proxy server. From what I understand, setting it to `$remote_addr` will indeed remove any existing entries in the header, and keep the original client IP, but not add the proxy server IP. Is there a way to do both? Clear any existing entires, add the client IP, and add the proxy server IP? If you have multiple reverse proxies chained together, you could use this on the first one, and use `$proxy_add_x_forwarded_for` on all others. – John Oct 26 '20 at 21:31
  • @John It shouldn't contain the IP of the proxy. It is an "X-Forwarded-For" header, meaning this req was forwarded for these IPs. Your proxied-to app will have the remote addr (the proxy) to look at if it needs it, and if your app is yet another proxy it will then add on the original proxy that called it to the XFF. If you include the proxy IP in it then it makes it look like it got passed to you on behalf of the proxy, which it didn't. The proxy did the passing. So you would only have a proxy IP in your XFF if it hit 2 separate proxies (the first proxy only is added by the second). – Jorden Jan 19 '21 at 20:07
  • @Jorden ok I think I follow. So `$proxy_add_x_forwarded_for` is not adding its own IP to the XFF list - it's adding the source IP it got the request from to the XFF list. In that case, setting the XFF header to `$remote_addr` makes sense. If you do have a chain of reverse proxies that follow, having the rest use `$proxy_add_x_forwarded_for` will work as expected. Thanks for the clarification – John Jan 19 '21 at 20:43
1

If anyone still have this issue, you can make use of "more_clear_input_headers" to keep only the address of last hop seen by Nginx.

more_clear_input_headers "X-Forwarded-For";

see the docs from openresty: https://github.com/openresty/headers-more-nginx-module#more_clear_input_headers

Youssef
  • 11
  • 1