撰于 阅读 250

使用 Cloudflare CDN 后获取访客真实 IP

在 Cloudflare 点开"小黄云"开启 CDN 后在 Nginx 日志的 IP 都是 Cloudflare 的 IP,那么怎么获取到访客的真实 IP 呢?

只需要在 Nginx 配置的 http 部分加入 Cloudflare 的 IP

Cloudflare IP 范围可以在这里找到Cloudflare IP 范围

不建议的方法

很多教程都是添加以下配置,但是这种方法有 IP 伪造的风险,不建议使用这种方法

set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;

方法一

在 Nginx 配置 http 部分加入以下部分就可以了

    # 设置 Cloudflare 的 IPv4 地址范围
    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;

    # 设置 Cloudflare 的 IPv6 地址范围
    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;

    # 真实客户端 IP 头
    real_ip_header CF-Connecting-IP;

方法二

如果你嫌这样看着太乱,可以在 Nginx 配置的目录新建一个cf.conf文件,文件内容如下

    # 设置 Cloudflare 的 IPv4 地址范围
    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;

    # 设置 Cloudflare 的 IPv6 地址范围
    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;

    # 真实客户端 IP 头
    real_ip_header CF-Connecting-IP;

然后在 Nginx 配置 http 部分加入以下内容

include cf.conf;

宝塔的 Nginx 配置目录在/www/server/nginx/conf

或者在其他地方新建cf.conf文件,那么就需要指定文件路径

include /www/server/panel/vhost/nginx/cf.conf;

方法三

自动获取和更新 Cloudflare IP 段

https://www.nenew.net/cloudflare-cdn-nginx-get-real-ip-tutorial.html
https://www.otakusay.com/140.html

配置完成后重载或重启 Nginx

重载 Nginx

sudo systemctl reload nginx

sudo service nginx reload

重启 Nginx

sudo systemctl restart nginx

sudo service nginx restart