TypechoJoeTheme

主机评测

主机评测

专注主机评测和优惠码发布

启用CDN后网站获取访客真实IP方法

2022-01-17
/
0 评论
/
730 阅读
/
正在检测是否收录...
01/17

最近手上一个网站由于流量每天达到>1.5T流量,我怀疑网站被恶意攻击(爬虫)随后想到了用全球知名CDN厂商Cloudflare来挡一波流量,顺便分析下到底是什么原因。
但是发现启用CDN之后,用户访问留下来的IP是不正确的,都是Cloudflare家CDN节点的IP地址,这个问题我以前工作遇到过。一般来说CDN厂商都采用了X-Forwarded-For和X-Real_IP等标准协议,所以本文介绍了获取用户真实IP的访问基本上适用于其它的CDN厂商。
由于我网站跑的web服务是nginx,需要用到ngx_http_realip_module模块。我默认安装nginx是没有把这个模块编译进去的。

一、Nginx编译ngx_http_realip_module

由于我用的是军哥提供的LNMP一键包,在lnmp安装目录下找到lnmp.conf编辑它,在Nginx_Modules_Options里加上realip,保存后执行./upgrade.sh nginx来升级下Nginx就可以了。命令如下:

cp /usr/local/nginx/sbin/nginx{,.bak}   #首先备份一下之前的nginx执行文件
Nginx_Modules_Options='--with-http_realip_module'
./upgrade.sh nginx

二、Nginx设置set_real_ip_from

编译好了ngx_http_realip_module,现在我们只需要在Nginx配置文件中添加set_real_ip_from代码,以下是我在cloudflare官网公布的节点IP上复制下来的 https://www.cloudflare.com/zh-cn/ips/ 示例如下:

vi /usr/local/nginx/conf/cloudflare_ip.conf
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/13;
set_real_ip_from 104.24.0.0/14;
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  X-Forwarded-For;
real_ip_recursive on;

三、引入到网站配置文件

然后再到你的网站配置文件中引入该文件:
include cloudflare_ip.conf;

四、安全设置

上面我们是通过安装ngx_http_realip_module和mod_remoteip模块获取到了用户真实的IP地址,但是有的时候我们需要借助Cloudflare 的安全防护功能来防止CC或者DDoS攻击,即仅允许Cloudflare CDN的IP访问我们的访问。

location / {
    allow 173.245.48.0/20
    allow 103.21.244.0/22
    allow 103.22.200.0/22
    allow 103.31.4.0/22;
    allow 141.101.64.0/18
    allow 108.162.192.0/1
    allow 190.93.240.0/20
    allow 188.114.96.0/20
    allow 197.234.240.0/2
    allow 198.41.128.0/17
    allow 162.158.0.0/15;
    allow 104.16.0.0/13;
    allow 104.24.0.0/14;
    allow 172.64.0.0/13;
    allow 131.0.72.0/22;
    allow 2400:cb00::/32;
    allow 2606:4700::/32;
    allow 2803:f800::/32;
    allow 2405:b500::/32;
    allow 2405:8100::/32;
    allow 2a06:98c0::/29;
    allow 2c0f:f248::/32;
    #Railgun IP
    deny  all;
}

五、重启你的nginx服务

service nginx restart
cdnCLOUDFLAREngx_http_realip_module
朗读
赞 · 3
赞赏
感谢您的支持,我会继续努力哒!

三合一收款

下面三种方式都支持哦

微信
QQ
支付宝
打开支付宝/微信/QQ扫一扫,即可进行扫码打赏哦
版权属于:

主机评测

本文链接:

https://zjpc.cc/958.html(转载时请注明本文出处及文章链接)

评论 (0)