How to log original value of $remote_addr when using Real-IP

michaelg asked:

My environment has user requests passing through a number of systems:

[Client] –> [ELB] —> [nginx] –> [web]

(ELB = AWS Elastic Load Balancer)

Thanks to this answer, I have nginx determining and passing the correct client IP address to the upstream servers (web) with the X-Forwarded-For and X-Real_IP headers. The relevant nginx config:

    real_ip_header      X-Forwarded-For;
    real_ip_recursive   on;
    proxy_set_header X-Real-IP $remote_addr;

My problem is this, the Real IP module in nginx replaces the existing $remote_addr variable with the result of its X-Forwarded-For calculations. This gives me the originating client IP, but I’m losing the IP address of the system that actually sent the request to the proxy (i.e. the ELB).

Overall, having the client IP is more important to me, but I would like to be able to log the full chain of requests so I can understand (and debug) how traffic is flowing. Currently, I can only have nginx log the client IP, its own IP, and the upstream server IP. I would like to be able to log the ELB IP as well.

I see X-Istence asked the same question in 2013, with little luck. Has anything changed or improved since then?

My answer:

You can get the original client address of the connecting ELB in the variable $realip_remote_addr, but be aware that this variable was only added in nginx 1.9.7, so you’ll need to be running a very recent version of nginx.

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.