在配置完CloudFlare后,查看Nginx的访问日志,发现IP都是CloudFlare的代理IP,如果不对日志作分析倒也无所谓,但是既然是折腾了,那么还是按照以前的办法将访问IP的问题解决一下。解决办法请按照如下步骤进行
1.定时获取CloudFlare的代理IP
在/data/script 目录下创建shell脚本,用来获取cloudflare的代理IP
mkdir -p /data/script vim /data/script/update_cf_ip.sh
填入如下内容,保存并退出。
#!/bin/bash echo "#Cloudflare" > /usr/local/nginx/conf/cloudflare_ip.conf; for i in `curl https://www.cloudflare.com/ips-v4`; do echo "set_real_ip_from $i;" >> /usr/local/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/nginx/conf/cloudflare_ip.conf; done echo "" >> /usr/local/nginx/conf/cloudflare_ip.conf; echo "# use any of the following two" >> /usr/local/nginx/conf/cloudflare_ip.conf; echo "real_ip_header CF-Connecting-IP;" >> /usr/local/nginx/conf/cloudflare_ip.conf; echo "#real_ip_header X-Forwarded-For;" >> /usr/local/nginx/conf/cloudflare_ip.conf;
创建/usr/local/nginx/conf/cloudflare_ip.conf文件。
touch /usr/local/nginx/conf/cloudflare_ip.conf
执行这个shell脚本,查看内容:
/bin/bash /data/script/update_cf_ip.sh
cat /usr/local/nginx/conf/cloudflare_ip.conf
以下内容便是shell脚本生成的内容:
#Cloudflare 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 104.16.0.0/12; set_real_ip_from 108.162.192.0/18; set_real_ip_from 131.0.72.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 162.158.0.0/15; set_real_ip_from 172.64.0.0/13; set_real_ip_from 173.245.48.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 190.93.240.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; set_real_ip_from 2400:cb00::/32; set_real_ip_from 2405:b500::/32; set_real_ip_from 2606:4700::/32; set_real_ip_from 2803:f800::/32; set_real_ip_from 2c0f:f248::/32; set_real_ip_from 2a06:98c0::/29; # use any of the following two real_ip_header CF-Connecting-IP; #real_ip_header X-Forwarded-For;
将其配置到crontab中,每周更新一次。
crontab -e
新增如下内容:
0 5 * * 1 /bin/bash /data/script/update_cf_ip.sh
2.配置Nginx
配置文件生成好以后便将其配置到nginx的配置文件中,编辑/usr/local/nginx/conf/vhost/myweb.conf文件。
vim /usr/local/nginx/conf/vhost/myweb.conf
在引入rewrite配置下面引入cloudflare_ip.conf配置。
include /usr/local/nginx/conf/rewrite/wordpress.conf; # 在这里引入配置文件 include /usr/local/nginx/conf/cloudflare_ip.conf;
校验配置文件是否正确:
nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
重新加载nginx
service nginx reload