· Updated

Get the real client IP in Nginx behind HAProxy

  • infrastructure

This article was written in 2019. Tools and versions have moved on since then, so some content may be outdated.

Docker

Define a header in haproxy configuration to set real client IP address

In haproxy, you can get the client IP address from the request and pass it to another proxy or application with a header.

  • %[src] is the client IP address extracted from incoming request.
  • X-Real-IP is the header we use to transfer IP address value.
frontend all_https
  option forwardfor header X-Real-IP
  http-request set-header X-Real-IP %[src]

Configure a custom log format in Nginx

  • Add a custom log format named “realip” (but name it the way you want…)
log_format realip '$http_x_real_ip - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';
  • Use it in your access_log directive
access_log /dev/stdout realip;
access_log /path_to/log/file realip;

← All posts