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?

2 Answers 2

11

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;
3
  • 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, 2020 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, 2021 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, 2021 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

2
  • Remember that this requires a third party module not included with nginx. Feb 19, 2021 at 17:19
  • Thanks @MichaelHampton, I forgot to mention that !
    – Youssef
    Feb 20, 2021 at 18:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .