从Google Cloud Load Balancer和cloudflare获取真正的IP

时间:2016-07-31 06:43:46

标签: ruby-on-rails nginx load-balancing google-compute-engine google-cloud-platform

我想获得真正的ip,我正在使用cloudflare和Google Cloud Network Load Balancer。

我把这个来源放到了nginx.conf

# Last updated Sat Jul 30 11:17:32 UTC 2016
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 199.27.128.0/21;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 130.211.0.0/22; #Google IP
real_ip_header X-Forwarded-For; #CF-Connecting-IP;

要检查我的IP,我制作了简单的导轨源。

return render :json => {:ip => request.ip, :remote_ip => request.remote_ip, :x_forwarded_for => request.env['HTTP_X_FORWARDED_FOR'], :client_ip => request.env['HTTP_CLIENT_IP'], :cf => request.env['CF-Connecting-IP']}

{"ip":"130.211.0.145","remote_ip":"130.211.0.145","x_forwarded_for":"(REAL IP), 141.101.85.141, 130.211.16.204, 130.211.0.145","client_ip":null,"cf":null}

但是ip不是我的ip,它是Google Cloud LoadBalancer。我该如何解决这个问题?我花了很多时间超过6个小时。

感谢。

1 个答案:

答案 0 :(得分:0)

CloudFlare Real IP标头在CF-Connecting-IP中可用,而CloudFlare发出X-Forwarded-For标头,看起来该标头会立即被覆盖。为了减轻这种影响,请改用此标头。

为了使用它,请务必确保您的nginx配置包含:

real_ip_header CF-Connecting-IP;

然后,您的应用程序可以从应用程序本身的REMOTE_ADDR环境变量中生成远程地址。