zoukankan      html  css  js  c++  java
  • Nginx 使用 sever 段规则屏蔽恶意 User Agent

    相对于 Apache,Nginx 占用的系统资源更少,更适合 VPS 使用。恶意的 User Agent 无处不在,博客更换到 WordPress 没几天,就被 SPAM(垃圾留言)盯上,又被暴力破解后台用户名密码。以前介绍过 Apache 使用 .htaccess 屏蔽恶意 User Agent,今天来介绍 Nginx 屏蔽恶意 User Agent的方法。
    
    先上规则&注释
    
    #禁用未初始化变量警告
    uninitialized_variable_warn off;
    #匹配各种 bad user agent,返回403错误
    if ($http_user_agent ~* "embeddedwb|NSPlayer|WMFSDK|qunarbot|mj12bot|ahrefsbot|Windows 98|MSIE 6.0; Windows 2000|EasouSpider|Sogou web spider") {
    return 403;
    }
    #匹配POST方法,给变量iftemp赋值
    if ($request_method ~* "POST") {set $iftemp X;}
    #匹配 bad user agent,给变量iftemp赋值;这几个UA主要是发垃圾留言的
    if ($http_user_agent ~* "MSIE 6.*NET|MSIE 7.*NET|MSIE 6.*SV1|MSIE 6.0; Windows NT 5.0") {
    set $iftemp "${iftemp}Y";
    }
    #如果变量iftemp符合上面两个条件,返回403错误
    if ($iftemp = XY) {return 403;}
    
    禁用未初始化变量警告,不然会不停写入警告到错误日志error.log,如下
    
    2014/09/11 09:21:11 [warn] 18649#0: *132 using uninitialized “iftemp” variable, client: 220.181.51.209, server: www.wilf.cn, request: “GET /wp-content/themes/dazzling/inc/fonts/glyphicons-halflings-regular.woff HTTP/1.0”, host: “www.wilf.cn”, referrer: “http://www.wilf.cn/”
    2014/09/11 09:21:11 [warn] 18649#0: *92 using uninitialized “iftemp” variable, client: 66.249.79.55, server: www.wilf.cn, request: “GET /page/14?mod=pad&act=view&id=741 HTTP/1.1”, host: “www.wilf.cn”
    
    Nginx 规则不支持2个以上的条件判断,绕个路,通过给变量两次赋值来完成2个条件判断。
    
    Nginx 规则也是使用正则表达式匹配字符串,分析日志,根据需要自己定制。
    
    检验成果的时候到了
    
    183.60.214.51 — [10/Sep/2014:22:16:18 +0800] — Bytes: 13507 — GET /?mod=pad&act=view&id=460 HTTP/1.1403 — – — Mozilla/5.0 (compatible; EasouSpider; +http://www.easou.com/search/spider.html) — – — –
    220.181.125.169 — [11/Sep/2014:09:38:15 +0800] — Bytes: 169 — GET /page/51?mod=wap&act=AddCom&inpId=860 HTTP/1.1403 — – — Sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07) — – — –
    
    EasouSpider 和 Sogou web spider,再也不见。
    
    附:搜索引擎蜘蛛爬虫一览
    
    更多 bad user agent:HackRepair.com Blacklist
  • 相关阅读:
    聪明人 & 普通人
    13种模型及方法论
    面向大规模商业系统的数据库设计和实践
    分治算法
    软件架构
    隐含前提思维模型
    Git回滚代码到某个commit
    使用arthas排查 test 问题
    Arthas
    docker 操作入门
  • 原文地址:https://www.cnblogs.com/archoncap/p/6132210.html
Copyright © 2011-2022 走看看