0. 前言

本站使用CloudFlare作为CDN,Typecho的Access插件记录的访问情况都是CloudFlare的地址,很不方便,Nginx支持解析客户端的真实地址。

1. 配置Nginx

  1. 查看已安装模块
  • 输入命令 nginx -V 查看安装的Nginx支持的模块
  • 如果输出里有--with-http_realip_module的话就不用重新编译Nginx了。
  1. 安装http_reqlip_module模块
    重新编译Nginx,带上--with-http_realip_module参数。

    2. 生成配置文件

    Bash脚本如下:

    #!/bin/bash
    filepath="/usr/local/nginx/conf/cloudflare_ip.conf"
    echo "#Cloudflare" > $filepath;
    for i in `curl https://www.cloudflare.com/ips-v4`; do
         echo "set_real_ip_from $i;" >> $filepath;
    done
    for i in `curl https://www.cloudflare.com/ips-v6`; do
         echo "set_real_ip_from $i;" >> $filepath;
    done
    echo "" >> $filepath;
    echo "# use any of the following two" >> $filepath;
    echo "real_ip_header CF-Connecting-IP;" >> $filepath;
    echo "#real_ip_header X-Forwarded-For;" >> $filepath;

输出文件示例:

#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;

# use any of the following two
real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For;

3. 修改网站对应的conf文件

引用刚刚生成的文件:include /usr/local/nginx/conf/cloudflare_ip.conf;

4. 自动更新IP列表

因为CloudFlare的IP可能会改变,建议把上面的脚本添加到定时任务,可以使用cron或者宝塔面板的计划任务,不再赘述。

最后修改:2019 年 11 月 30 日
Null