Nginx从Cloudflare获取真实IP配置

Nginx编译时应加入参数 –with-http_realip_module

修改使用Cloudflare的站点配置文件后,重启Nginx服务即可

server {
        #此处省略nginx其它参数配置
        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;
        real_ip_header CF-Connecting-IP;
        #real_ip_header X-Forwarded-For;
}

如果原本已经有了 X-Forwarded-For,可以新增 CF-Connecting-IP header 来完整的获取 source IP

要加入 log_format 可以使用 $http_cf_connecting_ip 和 $http_x_forwarded_for 用以验证

Cloudflare的IP段查询 https://www.cloudflare.com/zh-cn/ips/


另附自动更新脚本,请根据实际情况更改脚本参数

在Nginx配置目录创建cloudflare_ip.conf

touch /usr/local/webserver/nginx/conf/cloudflare_ip.conf

vi /usr/local/webserver/nginx/update_cloudflare_ip.sh 创建更新脚本

#!/bin/bash
echo "#Cloudflare" > /usr/local/webserver/nginx/conf/cloudflare_ip.conf;
for i in `curl https://www.cloudflare.com/ips-v4`; do
        echo "set_real_ip_from $i;" >> /usr/local/webserver/nginx/conf/cloudflare_ip.conf;
done
for i in `curl https://www.cloudflare.com/ips-v6`; do
        echo "set_real_ip_from $i;" >> /usr/local/webserver/nginx/conf/cloudflare_ip.conf;
done

echo "" >> /usr/local/webserver/nginx/conf/cloudflare_ip.conf;
echo "# use any of the following two" >> /usr/local/webserver/nginx/conf/cloudflare_ip.conf;
echo "real_ip_header CF-Connecting-IP;" >> /usr/local/webserver/nginx/conf/cloudflare_ip.conf;
echo "#real_ip_header X-Forwarded-For;" >> /usr/local/webserver/nginx/conf/cloudflare_ip.conf;

赋予脚本执行权限

chmod +x /usr/local/webserver/nginx/update_cloudflare_ip.sh

crontab -e 添加规则(每周一的凌晨1点自动执行更新脚本)

0 1 * * 1 /bin/bash /usr/local/webserver/nginx/update_cloudflare_ip.sh

最后在站点的配置文件结尾处}前,写入 include cloudflare_ip.conf; 即可