How to get your Client IPaddress with Nginx if you are using TCP on AWS ELB

If your Application is running behind an AWS Load Balancer (ELB) and you are using TCP ( for both 80 and 443).

You can run AWS ELB in different modes.

_1) You can do Load balance with HTTP/HTTPS traffic and if you use this one, the AWS ELB injects an X-Forwarded-For  header  that has the original client ipaddress. _

_2)  You can do Load balance straight with TCP traffic. If you use this mode, your application can use Websockets. But it won’t provide the X-Forwarded-For  header because the load balancer doesn’t know anything about HTTP headers in this case. So it’s hard to track the Client IP address. However we can do this with an AWS ELB feature called “Proxy Protocol” _

_ _

**Here I am using Ubuntu distro with Nginx version 1.9.0 **

[color-box color="green”]

sudo add-apt-repository ppa:chris-lea/nginx-devel

sudo apt-get update

sudo apt-get -y install nginx-full

[/color-box]

Your AWS ELB Listeners Looks like the below one

vu

Now you need to enable Proxy Protocol on the AWS ELB

First create a load balancer policy using the below command

[color-box color="green”]

aws elb create-load-balancer-policy –load-balancer-name vishnudxb  –policy-name vishnudxb-ProxyProtocol-policy –policy-type-name ProxyProtocolPolicyType –policy-attributes AttributeName=ProxyProtocol,AttributeValue=true

[/color-box]

Now we need to enable the Newly created policy on the specified ports. (ie 80 & 443)

[color-box color="green”]

aws elb set-load-balancer-policies-for-backend-server –load-balancer-name vishnudxb –instance-port 80 –policy-names vishnudxb-ProxyProtocol-policy

aws elb set-load-balancer-policies-for-backend-server –load-balancer-name vishnudxb –instance-port 443 –policy-names vishnudxb-ProxyProtocol-policy

[/color-box]

Now we need to configure Nginx for Proxy Protocol

Add the below entries on your /etc/nginx/nginx.conf

[color-box color="green”]

log_format elb_log ‘$proxy_protocol_addr - $remote_user [$time_local] ' ‘“$request” $status $body_bytes_sent “$http_referer” ' ‘“$http_user_agent”';

[/color-box]

Now you need to do some changes on your sites-enabled like below:

vu

vu

**And finally you can see the Client IP address on your Nginx logs  when you use AWS ELB TCP traffic straight. **

vu