对于做国内网站来说,我不希望国外蜘蛛来访问我的网站,这些垃圾流量多了之后,严重浪费服务器的带宽和资源。通过判断user agent,在nginx中禁用这些蜘蛛可以节省一些流量,也可以防止一些恶意的访问。

解决方案
修改nginx.conf,禁止网络爬虫的user_agent,返回403。

1、 进入nginx的配置目录,例如cd /usr/local/nginx/conf
2、添加agent_deny.conf配置文件 vim agent_deny.conf

#禁止Scrapy等爬虫工具的抓取 Baiduspider
if ($http_user_agent ~* "Scrapy|Sogou web spider") {
  return 403;
}

#禁止指定UA及UA为空的访问
if ($http_user_agent ~ "Scrapy|SemrushBot|FeedDemon|JikeSpider|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|CoolpadWebkit|Java|Feedly|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|YisouSpider|HttpClient|MJ12bot|heritrix|EasouSpider|LinkpadBot|Ezooms|^$" )
{
  return 403;
}
#禁止非GET|HEAD|POST方式的抓取
if ($request_method !~ ^(GET|HEAD|POST)$) {
  return 403;
}

#添加针对特殊的user_agent的访问

if ($http_user_agent ~ "Mozilla/4.0\ \(compatible;\ MSIE\ 6.0;\ Windows\ NT\ 5.1;\ SV1;\ .NET\ CLR\ 1.1.4322;\ .NET\ CLR\ 2.0.50727\)") { 
   return 404;
}

在server层的网站配置中include这个配置文件进来,nginx -t 测试配置格式是否通过,再重启nginx服务

然后测试一下
用curl命令模拟浏览器头信息, 设置是否成功,curl的-A 可以让我们随意指定自己这次访问所宣称的自己的浏览器信息

#curl -I -A “BaiduSpider” www.test.com

HTTP/1.1 200 OK
Server: nginx
Date: Mon, 09 Feb 2022 09:37:20 GMT
Content-Type: text/html; charset=UTF-8 Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.19 Vary: Accept-Encoding, Cookie
Cache-Control: max-age=3, must-revalidate
WP-Super-Cache: Served supercache file from PHP

#curl -I -A “JikeSpider” www.test.com

HTTP/1.1 403 Forbidden
Server: nginx Date: Mon, 09 Feb 2022 09:37:44 GMT
Content-Type: text/html
Content-Length: 162 Connection: keep-alive

nginx通过判断User-Agent屏蔽蜘蛛访问网站就已经完成,可以根据实际情况对agent_deny.conf中的蜘蛛进行增加、删除或者修改。

2、网站根目录下增加Robots.txt,放在站点根目录下。
http://tool.chinaz.com/robots/站点可以针对现在的搜索引擎按照想要的规则生成robots.txt文件。

标签: none

添加新评论