Location based whitelisting of IP's on nginx webservers behind Elastic Load Balancer

linuxtester asked:

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?

My 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; # Netblock for my ELB's

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.