站长资源服务器

Nginx防盗链根据UA屏蔽恶意User Agent请求(防蜘蛛)

整理:jimmy2024/10/8浏览2
简介相对于 Apache,Nginx 占用的系统资源更少,更适合 VPS 使用。恶意盗链的 User Agent 无处不在,博客更换到 WordPress 没几天,就被 SPAM(垃圾留言)盯上,又被暴力破解后台用户名密码。以前介绍过 Apache 使用 .htaccess 屏蔽恶意 User Agen

相对于 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"codetitle">复制代码 代码如下:
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,再也不见。