欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何使用Nginx防止特定用户代理(User Agent)进行网站爬取的服务器防爬策略指南

最编程 2024-07-24 08:11:59
...

网络上的爬虫非常多,有对网站收录有益的,比如百度蜘蛛(Baiduspider),也有不但不遵守robots规则对服务器造成压力,还不能为网站带来流量的无用爬虫,比如宜搜蜘蛛(YisouSpider)。

下面介绍怎么禁止这些无用的user agent访问网站。

 

进入到nginx安装目录下的conf目录,将如下代码保存为 agent_deny.conf

cd /usr/local/nginx/conf

vim agent_deny.conf

#禁止Scrapy等工具的抓取
if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) 
{
     return 403;
}
#禁止指定UA及UA为空的访问
if ($http_user_agent ~ "Baiduspider|WinHttp|WebZIP|FetchURL|node-superagent|java/|FeedDemon|Jullo|JikeSpider|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|Java|Feedly|Apache-HttpAsyncClient|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|HttpClient|MJ12bot|heritrix|EasouSpider|Ezooms|BOT/0.1|YandexBot|FlightDeckReports|Linguee Bot|^$"  ) 
{
     return 403;            
}
#禁止非GET|HEAD|POST方式的抓取
if ($request_method !~ ^(GET|HEAD|POST)$) 
{
    return 403;
}

然后,在网站相关配置中的  location / {  之后插入如下代码:

include agent_deny.conf;

 

保存后,执行如下命令,平滑重启nginx即可:

/usr/local/nginx/sbin/nginx -s reload

 

模拟宜搜蜘蛛的抓取:

curl -I -A 'YisouSpider'  http://网站链接

结果返回403

 

模拟UA为空的抓取:

curl -I -A '' http://网站链接

结果返回403

 

模拟百度蜘蛛的抓取:

curl -I -A 'Baiduspider'  http://网站链接

结果返回200

 

下面是网络上常见的垃圾UA列表

FeedDemon             内容采集
BOT/0.1 (BOT for JCE) sql注入
CrawlDaddy            sql注入
Java                  内容采集
Jullo                 内容采集
Feedly                内容采集
UniversalFeedParser   内容采集
ApacheBench           cc攻击器
Swiftbot              无用爬虫
YandexBot             无用爬虫
AhrefsBot             无用爬虫
YisouSpider           无用爬虫
jikeSpider            无用爬虫
MJ12bot               无用爬虫
ZmEu phpmyadmin       漏洞扫描
WinHttp               采集cc攻击
EasouSpider           无用爬虫
HttpClient            tcp攻击
Microsoft URL Control 扫描
YYSpider              无用爬虫
jaunty                wordpress爆破扫描器
oBot                  无用爬虫
Python-urllib         内容采集
Indy Library          扫描
FlightDeckReports Bot 无用爬虫
Linguee Bot           无用爬虫