先上规则&注释
#禁用未初始化变量警告 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.1 — 403 — – — 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.1 — 403 — – — Sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07) — – — –
EasouSpider 和 Sogou web spider,再也不见。