Real IP from Amazon Load Balancers

If you are running an EC2 instance behind an Amazon Elastic Load Balancer (ELB), you’ll find that the visitors’ IPs are hided behind the load balancer, so your application cannot get the clients’ real IPs. In fact, visitors’ original IPs are passed via a X-Forwarded-For information in the header (http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/x-forwarded-headers.html), so we can easily get it in our application code. However, it is more convenient for us to get the real IP automatically without additional parsing data. So this quick tutorial will guide you how to get Real IP from Amazon Load Balancers in your NginX server setting.

The work is simply add the following directives into http {} block in your nginx server setting:

[bash]real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;[/bash]

There is one down side of the above approach: if anyone directly accesses your EC2 server, they would be able to spoof an X-Forwarded-For header and NginX would use the wrong vistor’s IP. In order to overcome this, you can ping the IP of your ELB and set it in set_real_ip_from as follows (assume that your ELB IP is 11.22.33.44):

[bash]real_ip_header X-Forwarded-For;
set_real_ip_from 11.22.33.44;[/bash]

That is all 🙂

Leave a Reply