IP blocking in Nginx behind AWS cloudfront

Eran Goldman-Malka · September 23, 2021

New day new task without Stackoverflow solution.

My goal was to block the /admin endpoint for users outside of the company IP scope.

After a long search in Google and StackOverflow, I got some ideas for doing it, but I couldn’t find a simple solution.

The main problem is that Cloud front overrides the client IP and moves it to the X_FORWARDED_FOR header field. And also, the ELB moved there another IP and so on.

Long story short, the solution is going recursively on the X_FORWARDED_FOR header field and finding the first, which is the actual client IP.

Add to your Nginx conf the following lines :

map $http_x_forwarded_for $real_ip {
    ~^(\d+\.\d+\.\d+\.\d+) $1;
    default $remote_addr;
}

geo $real_ip $giveaccess {
      default 0;
      [Fisrt-IP] 1;
      [Second-IP] 1;
      ..
}

..
server {
  ..
  location /admin {
    if ($giveaccess = 0){
      #redirect the user to index or another place in the app
      return 302 $scheme://example.tld
    }
  }
  ..
}

Twitter, Facebook