使用多层反向代理或多家不同CDN时,获取客户端真实IP的方法

为了实现手头各网站的全球 CDN 加速与攻击防御,笔者针对中国大陆境内与境外线路分别采用了 GeoDNS 分流,并在最外层使用不同厂家提供的 CDN。其中,国内 CDN 通过 Nginx 支持的 X-Forwarded-For 标头获取客户端真实IP,国外线路使用 CloudFlare,以 CF-Connecting-IP 作为标头获取客户端真实IP。而这两种标头在 Nginx 中默认无法共存,需要修改配置文件以达到目的。具体配置如下,使用时可依不同 CDN 厂商的配置酌情修改:

本文由逸成博客 (blog.ensonyan.com) 首发,未经授权请勿转载,谢谢配合。

# Range Start
    # Not CloudFlare's Range
    set_real_ip_from 27.221.*.* /24;
    set_real_ip_from 103.135.*.* /24;
	
    #CloudFlare
    set_real_ip_from 173.245.48.0/20;
    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 141.101.64.0/18;
    set_real_ip_from 108.162.192.0/18;
    set_real_ip_from 190.93.240.0/20;
    set_real_ip_from 188.114.96.0/20;
    set_real_ip_from 197.234.240.0/22;
    set_real_ip_from 198.41.128.0/17;
    set_real_ip_from 162.158.0.0/15;
    set_real_ip_from 104.16.0.0/12;
    set_real_ip_from 172.64.0.0/13;
    set_real_ip_from 131.0.72.0/22;
    set_real_ip_from 2400:cb00::/32;
    set_real_ip_from 2606:4700::/32;
    set_real_ip_from 2803:f800::/32;
    set_real_ip_from 2405:b500::/32;
    set_real_ip_from 2405:8100::/32;
    set_real_ip_from 2a06:98c0::/29;
    set_real_ip_from 2c0f:f248::/32;
    
    # My Server
    set_real_ip_from xxx.xxx.xxx.xxx;
	
# Range End


# EnsonYan.com config and other Configs
geo $realip_remote_addr $use_x_real_ip {
	default 0;
    # Retype EnsonYan.com and YAN.net.cn server IPs
	  xxx.xxx.xxx.xxx/24 1;
	  xxx.xxx.xxx.xxx 1;
}

# CloudFlare
geo $realip_remote_addr $use_x_cf_connecting_ip {
	default 0;
	173.245.48.0/20 1;
	103.21.244.0/22 1;
	103.22.200.0/22 1;
	103.31.4.0/22 1;
	141.101.64.0/18 1;
	108.162.192.0/18 1;
	190.93.240.0/20 1;
	188.114.96.0/20 1;
	197.234.240.0/22 1;
	198.41.128.0/17 1;
	162.158.0.0/15 1;
	104.16.0.0/13 1;
	104.24.0.0/14 1;
	172.64.0.0/13 1;
	131.0.72.0/22 1;
  	2400:cb00::/32 1;
  	2606:4700::/32 1;
  	2803:f800::/32 1;
  	2405:b500::/32 1;
  	2405:8100::/32 1;
  	2a06:98c0::/29 1;
  	2c0f:f248::/32 1;
}

map "$use_x_real_ip:$use_x_cf_connecting_ip" $real_ip {
  default $http_x_forwarded_for;
  "1:0" $http_x_real_ip;
  "0:1" $http_cf_connecting_ip;
}

#more_set_input_headers "X-IP: $real_ip";
#real_ip_header X-IP;
real_ip_recursive on;

经过测试,以 www.yan.net.cn逸成博客 为例,所有访客的真实IP均可被正确获取。

本文采用 CC BY-NC-SA 3.0 Unported 协议进行许可
所有摄影作品、媒体文件等,未经授权严禁转载。
# # # # # # #
首页      信息技术      使用多层反向代理或多家不同CDN时,获取客户端真实IP的方法
EnsonYan

EnsonYan

文章作者

关于我的详细介绍,请在主页左上角菜单栏中“关于站长”内查看!

发表评论

textsms
account_circle
email

使用多层反向代理或多家不同CDN时,获取客户端真实IP的方法
为了实现手头各网站的全球 CDN 加速与攻击防御,笔者针对中国大陆境内与境外线路分别采用了 GeoDNS 分流,并在最外层使用不同厂家提供的 CDN。其中,国内 CDN 通过 Nginx 支持的 X-Forwar…
扫描二维码继续阅读
2022-05-08