zoukankan      html  css  js  c++  java
  • Nginx屏蔽个别User-Agent蜘蛛访问网站的方法

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

    步骤

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

    2、添加agent_deny.conf配置文件

    #禁止Scrapy等工具的抓取
    if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) {
      return 403;
    }
    #禁止指定UA及UA为空的访问
    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|^$" )
    {
      return 403;
    }
    #禁止非GET|HEAD|POST方式的抓取
    if ($request_method !~ ^(GET|HEAD|POST)$) {
      return 403;
    }
    

    3、在网站相关配置文件中插入代码“include agent_deny.conf ;”。

    location ~ [^/].php(/|$)
    {
      try_files $uri =404;
      fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_index index.php;
      include fastcgi.conf;
      include agent_deny.conf ;
    }
    

    4、重新加载nginx

    /etc/init.d/nginx reload

    测试

    通过curl模拟蜘蛛抓取访问。

    root@vm-199:~# curl -I -A "BaiduSpider" www.sijitao.net
    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
    
    root@vm-199:~# curl -I -A "JikeSpider" www.sijitao.net           
    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
    
    root@vm-199:~# curl -I -A "" www.sijitao.net             
    HTTP/1.1 403 Forbidden
    Server: nginx
    Date: Mon, 09 Feb 2015 03:37:52 GMT
    Content-Type: text/html
    Content-Length: 162
    Connection: keep-alive

    nginx日志上的效果如下。

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

  • 相关阅读:
    SpringMVC(四)-- 文件下载、自定义拦截器、异常处理
    SpringMVC(三)-- 视图和视图解析器、数据格式化标签、数据类型转换、SpringMVC处理JSON数据、文件上传
    SpringMVC(二)--处理数据模型、ModelAndView、Model、Map、重定向、@ModelAttribute、
    SpringMVC(一)--基础、REST、@RequestParam、POST请求乱码等
    反射
    servlet基础
    eclipse为项目设置jdk
    mysql创建表时符号``的作用
    redis进阶
    相对路径和绝对路径的区别
  • 原文地址:https://www.cnblogs.com/out8/p/4331909.html
Copyright © 2011-2022 走看看