nginx根据http_user_agent来拦截访问

原文链接https://blog.csdn.net/qq_22929803/article/details/50724662

1、进入nginx的配置目录,例如cd /usr/local/nginx/conf

2、添加agent_deny.conf配置文件 vim agent_deny.conf

  1. #禁止Scrapy等工具的抓取
  2. if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) {
  3. return 403;
  4. }
  5. #禁止指定UA及UA为空的访问
  6. if ($http_user_agent ~ "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|^$" )
  7. {
  8. return 403;
  9. }
  10. #禁止非GET|HEAD|POST方式的抓取
  11. if ($request_method !~ ^(GET|HEAD|POST)$) {
  12. return 403;
  13. }

还有加一些针对特殊的user_agent的访问 

  1. 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)") {
  2. return 404;
  3. }

 这个是如何得出是频繁访问的user_agent呢,通过分析nginx的日志可以得出

tail -n 1000 /usr/local/nginx/logs/access.log | awk -F" '{A[$(NF-1)]++}END{for(k in A)print A[k],k}' | sort -n | tail 分析访问次数

执行以上命令可以得出访问最多的user_agent,通过人为判断是否正常来屏蔽
然后在nginx.conf的location中加入include agent_deny.conf;

注意:include agent_deny.conf是放到location下面

平滑重启nginx

/usr/local/nginx/sbin/nginx –s reload

然后测试一下 设置是否成功


curl -I -A "BaiduSpider" www.test.com


HTTP/1.1 200 OK
Server: nginx
Date: Mon, 09 Feb 2015 03: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 2015 03:37:44 GMT
Content-Type: text/html
Content-Length: 162 Connection: keep-alive
到这里,nginx通过判断User-Agent屏蔽蜘蛛访问网站就已经完成,可以根据实际情况对agent_deny.conf中的蜘蛛进行增加、删除或者修改。

原文地址:https://www.cnblogs.com/kaishirenshi/p/12530523.html