7

My nginx backend server should only accept requests from my frontend, 1.2.3.4. However, I also want nginx to log the correct IP address, so I use set_real_ip_from. But by doing this, the allow rule in the config isn't matched, and nginx will always return a 403. Here's the relevant config:

allow  1.2.3.4;
deny  all;

set_real_ip_from  1.2.3.4;
real_ip_heaader  X-Real-IP;

How can I overcome this problem?

Jay
  • 81
  • 1
  • 2
  • Why not just don't use `set_real_ip` and log `X-Real-IP` header? – Alexey Ten Aug 21 '15 at 07:15
  • Because those are used when your app is being accessed via a proxy (e.g. Amazon ELB) and so all traffic comes from a single IP address; if you don't use those you can't filter. – El Yobo Dec 17 '15 at 22:16

1 Answers1

4

I was looking for this myself and as it took me a "while" to find a solution I'll put it here to ease it for others.

allow/deny constructs won't work in this case since they don't work with real ip variables.

Instead you can use $http_x_forwarded_for variable:

## this goes before server section
## it allows us to check if forwarded ip is allowed to make request or not
map $http_x_real_ip $allowed {
    default false;

    ## your ip goes here
    ~\s111.111.111.111 true;
    ## other ips you want to allow
}

server {
    ## ... other instructions...

    set_real_ip_from  1.2.3.4;
    real_ip_header  X-Forwarded-For;

    ## you may want to add this to get "truly" real ip
    real_ip_recursive  on;

    ## ... other instructions...

    ## or any other location you need
    location / {
        if ($allowed = false) {
            return 403;
        }
        ## ... other instructions...
    }
}