MENU

启用Cloudflare CDN后网站获取用户真实IP(宝塔面板)

May 22, 2023 • 已被 298 位童鞋围观过 • 代码分享,教程文章

最近在维护一个站点时候,开启了Cloudflare免费的CDN服务,随后发现了一个问题,就是使用了Cloudflare CDN后,网站获取到的IP地址都是Cloudflare的CDN节点的,不能得到真实用户的IP地址,防御效果大大折扣。好在Cloudflare已经为我们想到这一点了,将访问者的 IP 地址包含在 X-Forwarded-For 标头和 CF-Connecting-IP 标头。

有了 X-Forwarded-For 标头,如果是Nginx可以使用ngx_http_realip_module模块,如果是Apache,则可以使用mod_remoteip模块来获取用户的真实IP。本篇文章就来分享一下如何编译和启用ngx_http_realip_module模块和mod_remoteip模块来获取用户的真实IP地址。(仅限于宝塔面板)。

其实方法很简单,宝塔环境下的Nginx已经编译安装了 ngx_http_realip_module模块,我们只需要在在配置中启用即可。
进入 网站--->设置----> 找到配置文件 添加一下的代码

    location / {
       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/13;
       set_real_ip_from 104.24.0.0/14;
       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;
       # use any of the following two
       real_ip_header CF-Connecting-IP;
       #real_ip_header X-Forwarded-For;
     }

#重启Nginx 即可实现

IP时间更新在 2023年5月22日23:39:44

一般来说CloudFlare的IP地址是不会变的,你可以在这里找到:https://www.cloudflare.com/ips/

<?php
#获取CloudFlare CDN下用户的真实IP
function Get_real_ip(){
    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $userIP = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } else {
        $userIP = $_SERVER['REMOTE_ADDR'];
    }
    return $userIP;
}


?>
Last Modified: September 28, 2023