在Nginx日志中的User Agent内容,找出恶意爬虫

禁止恶意爬虫访问你的网站

robots.txt

恶意爬虫不会看robots.txt文件,且频率很高。

# 每个组都以 User-agent 行开头,该行指定了组适用的目标;但Sitemap只有一行。Allow与Disallow的行要以/开始,支持通配符,$代表URL结尾。
User-agent: *
Disallow: /wp-admin/
Disallow: /wp-content/
Allow: /wp-content/uploads/20
Disallow: /wp-includes/

Sitemap: https://blog.t725.cn/wp-sitemap.xml

Nginx 的日志配置

  1. 默认日志格式配置就可以了,里面有 “$http_user_agent”
    log_format main
        # 客户端地址 - 客户端用户名 "服务器时间" "请求方法 URI HTTP协议" 响应状态码 响应内容大小bytes
        '$remote_addr - $remote_user "$time_local" "$request" $status $body_bytes_sent '
        # "url跳转来源" "浏览器UA信息" 
        '"$http_referer" "$http_user_agent"'
  1. 每个域名使用独立的日志文件:在 server 的 server_name 后面指定
        if ($time_iso8601 ~ "^(\d{4})-(\d{2})") {
            set $year $1;
            set $month $2;
        }
        access_log  logs/access-$year$month-$host.log main;

日志文件分析

小站流量不高,每个月的日志文件导入excel里分析就可以了。

  1. 导入成功后,重命名sheet为logs,将user_agent列复制到另一个sheet里,除重+排除
  2. 再做辅助列,用函数计算:注意SEARCH不区分大小写,FIND是区分大写
count =COUNTIF('logs'!J:J,A2)
bot =if(OR(IFERROR(SEARCH("Bot",A2),0)>0,IFERROR(SEARCH("Spider",A2),0)>0),1,0)
  1. 后看 count 大于N的记录,N值根据自己情况的定。
  2. 找出恶意爬虫的关键字

更新Nginx配置,拦截恶意爬虫访问

在 server 的 第一个 location 之前,增加以下内容:

        # 禁止特定bot,if中 ~*:与正则表达式匹配为真,不区分大小写;!~*:为不匹配;=:为精确匹配;!=:为精确不匹配。
        if ($http_user_agent ~* (python|perl|Go-http-client|fasthttp|Apache|zgrab|Custom-AsyncHttpClient|Amazonbot|MJ12bot|AhrefsBot)) {
            return 444;
        }
        if ($http_user_agent = -) {
            return 444;
        }
        if ($http_user_agent = "") {
            return 444;
        }

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注