My nginx backend server should only accept requests from my frontend, 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:

deny  all;

real_ip_heaader  X-Real-IP;

How can I overcome this problem?

  • Why not just don't use set_real_ip and log X-Real-IP header?
    – Alexey Ten
    Aug 21 '15 at 7: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

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...

    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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.