Search code examples
nginxgoogle-cloud-platformgoogle-cloud-load-balancer

GCP CLB: how to get X-Forwarded-For IP in Nginx.conf?


According GCP doc, https://cloud.google.com/load-balancing/docs/https#target-proxies, X-Forwarded-For contains multiple IPs, eg 1.2.3.4, 5.6.7.8, where 1.2.3.4 is the real client IP, 5.6.7.8 is the CLB IP.

How can I get 1.2.3.4 in nginx.conf? I want to use it with geoip.


Solution

  • You can use the real IP module to break down X-Forwarded-For and set the $remote_addr variable with the proper value.

    For example:

    set_real_ip_from  5.6.7.8;
    real_ip_header    X-Forwarded-For;
    real_ip_recursive on;
    

    The value of $remote_addr is changed from 5.6.7.8 to 1.2.3.4.

    In many distributions of Nginx, this module is already present. Use nginx -V to confirm which modules are present.