2

How do I enable both X-Real-IP and X-Forwarded-For in Nginx? I currently have the following to get real IPs in Docker network.

set_real_ip_from  172.18.0.0/32;
real_ip_header    X-Real-IP;
real_ip_recursive on;

I would also like to pass real IPs from Cloudflare to Docker containers as well. How do I use both X-Real-IP and X-Forwarded-For in same configuration, one set of IPs for X-Real-IP and one set of IPs for X-Forwarded-For?

2 Answers 2

2

If you're trying to get real IPs from behind CloudFlare, you should instead use their own header, CF-Connecting-IP. You should ignore the other headers if you haven't generated them yourself, as they may be faked by the client.

real_ip_header CF-Connecting-IP;
0
  1. Try mapping them (doesn't work):

    map $remote_addr $real_header {
      default X-Real-IP;
      172.18.0.1 X-Forwarded-For;
    }
    
    server {
      real_ip_header $real_header;
    }
    
  2. Try separating those streams into different servers. As per manual real_ip_header can be set per server or location, so you can:

    server {
      listen :8080;
      real_ip_header X-Real-IP;
      include "/all/other/stuff.conf";
    }
    
    server {
      listen :8081;
      real_ip_header X-Forwarded-For;
      include "/all/other/stuff.conf";
    }
    
  3. Playing with locations will include a lot more syntax sugar to separate them and you will probably need to use if's, but they are evil. But I think it's quite possible to create two internal locations with a manual internal rewrite between those two. This will be totally hidden from the user.

  4. I suppose playing with Lua might also help, but please try previous suggestions first.

2
  • 1
    Have you tried this? Many nginx directives do not accept variables. Mar 10, 2018 at 16:55
  • Err, you are right. It doesn't give any errors but it just doesn't work. Anyway I'll just add a few other ideas I got. All of them require testing anyway as this situation isn't common.
    – kworr
    Mar 11, 2018 at 14:55

You must log in to answer this question.

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