该文章转载自:Charles’s Blog,点击上面转载来源可以跳转到原文
在配置完 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