在配置完CloudFlare后,查看Nginx的访问日志,发现IP都是CloudFlare的代理IP,如果不对日志作分析倒也无所谓,但是既然是折腾了,那么还是按照以前的办法将访问IP的问题解决一下。解决办法请按照如下步骤进行。

1.定时获取CloudFlare的代理IP

在/data/script 目录下创建shell脚本,用来获取cloudflare的代理IP

1
2
mkdir -p /data/script
vim /data/script/update_cf_ip.sh

填入如下内容,保存并退出。

1
2
3
4
5
6
7
8
9
10
11
12
#!/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文件。

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

执行这个shell脚本,查看内容:

1
2
3
/bin/bash /data/script/update_cf_ip.sh

cat /usr/local/nginx/conf/cloudflare_ip.conf

以下内容便是shell脚本生成的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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

1
2
real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For;

将其配置到crontab中,每周更新一次。

1
crontab -e

新增如下内容:

1
0 5 * * 1 /bin/bash /data/script/update_cf_ip.sh

2.配置Nginx

配置文件生成好以后便将其配置到nginx的配置文件中,编辑/usr/local/nginx/conf/vhost/myweb.conf文件。

1
vim /usr/local/nginx/conf/vhost/myweb.conf

在引入rewrite配置下面引入cloudflare_ip.conf配置。

1
include /usr/local/nginx/conf/rewrite/wordpress.conf;
1
2
#在这里引入配置文件
include /usr/local/nginx/conf/cloudflare\_ip.conf;

校验配置文件是否正确:

1
2
3
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

1
service nginx reload