Nginx – Location based whitelisting of IP’s on nginx webservers behind Elastic Load Balancer

amazon-web-servicesnginxx-forwarded-for

I run nginx webservers behind an elastic load balancer in AWS.
The real IP is got through X-Forwarded-For.
The issue faced is how to use this to deny all and whitelist only specific sources for particular locations.

Something like:
location /test/ {
include /etc/nginx/allowed-XForwardedFor.conf;
deny all;
}

Can I catch the X-Forwarded-For IP's with a variable and then use it in the conf file or in some-way use it with the allow option in locations or do it with the help of an if conditional?

Best Answer

Use the nginx realip module, and then you don't have to worry about the X-Forwarded-For header; you can just act on IP addresses as if the load balancer wasn't there.

A sample configuration:

http {
        real_ip_header X-Forwarded-For;
        set_real_ip_from 172.19.0.0/16; # Netblock for my ELB's