Nginx anti hotlinking requests of anti spider according to UA block malicious User Agent
- 2020-05-10 23:31:41
- OfStack
Compared with Apache, Nginx occupies less system resources and is more suitable for VPS. The malicious hotlinking User Agent is everywhere. Within a few days after changing to WordPress, the blog was targeted by SPAM (spam), and the background user name password was cracked by violence. Having previously described Apache's use of.htaccess to block malicious User Agent, today we present Nginx's method of blocking malicious User Agent requests.
Start with rules & comments
# Disable uninitialized variable warnings
uninitialized_variable_warn off;
# Matching a variety of bad user agent To return to 403 error
if ($http_user_agent ~* "embeddedwb|NSPlayer|WMFSDK|qunarbot|mj12bot|ahrefsbot|Windows 98|MSIE 6.0; Windows 2000|EasouSpider|Sogou web spider") {
return 403;
}
# matching POST Method, give the variable iftemp The assignment
if ($request_method ~* "POST") {set $iftemp X;}
# matching bad user agent To variable iftemp The assignment ; This a few UA It's mostly spam
if ($http_user_agent ~* "MSIE 6.*NET|MSIE 7.*NET|MSIE 6.*SV1|MSIE 6.0; Windows NT 5.0") {
set $iftemp "${iftemp}Y";
}
# If the variable iftemp Satisfies the above two conditions, returns 403 error
if ($iftemp = XY) {return 403;}
Disable uninitialized variable warnings, otherwise they will be repeatedly written to the error log error.log, as shown below
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 "
The Nginx rule does not support more than two conditional judgments. Instead, take a detour and complete two conditional judgments by assigning a variable twice.
The Nginx rule also USES regular expressions to match strings, analyze logs, and customize as needed.
It's time to check the results
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 and Sogou web spider, no more.