nginx多条件判断

作者: ropon 分类: 经验分享 发布时间: 2019-05-14 09:12
#比如过滤大量POST首页恶意请求

以下规则可编写在 标签段:server,location
set $flag 0;
if ($request_method ~ ^(POST)$) {
	set $flag "${flag}1";
}
#if ($document_uri ~ ^(/)$) {
if ($request_uri ~ ^(/)$) {
	set $flag "${flag}2";
}
if ($flag = "012") {
	return 403;
}

#开启rewrite log 日志分析

rewrite_log on;
error_log /home/wwwlogs/dev2.ropon.top_nginx_error.log notice;

2019/05/14 09:10:34 [notice] 7317#0: *10 "^(POST)$" matches "POST", client: 127.0.0.1, request: "POST / HTTP/1.1", host: "dev2.ropon.top"
2019/05/14 09:10:34 [notice] 7317#0: *10 "^(/)$" matches "/", client: 127.0.0.1, request: "POST / HTTP/1.1", host: "dev2.ropon.top"

[14/May/2019:09:10:34 +0800] "POST / HTTP/1.1" 403 162 "-" "PostmanRuntime/7.6.0"
[14/May/2019:09:15:31 +0800] "POST /login HTTP/1.1" 200 43 "-" "PostmanRuntime/7.6.0"

大量POST 请求有规律页面,且IP分散

127.0.0.1 - - [17/May/2019:08:49:23 +0800] "POST /12-3-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:02 +0800] "POST /12-3-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:02 +0800] "POST /12-3-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:02 +0800] "POST /12-3-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:17 +0800] "POST /12-31-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:20 +0800] "POST /11-31-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:23 +0800] "POST /11-31-2.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:26 +0800] "POST /14-31-2.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:31 +0800] "POST /4-31-2.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:33 +0800] "POST /4-1-2.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:35 +0800] "POST /4-1-2.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:37 +0800] "POST /4-1-1.html HTTP/1.1" 403 162 "-" 
127.0.0.1 - - [17/May/2019:08:51:40 +0800] "POST /4-6-1.html HTTP/1.1" 403 162 "-" 

同理修改下rewrite规则
if ($request_uri ~ ^(/([1-9]+)-([1-9]+)-([1-9]+)\.html)$) {
	set $flag "${flag}2";
}

查看rewrite log
[notice] 21483#0: *1 "^(POST)$" matches "POST", client: 127.0.0.1, : "POST /4-6-1.html HTTP/1.1", host: "dev2.ropon.top"
[notice] 21483#0: *1 "^(/([1-9]+)-([1-9]+)-([1-9]+)\.html)$" matches "/4-6-1.html", client: 127.0.0.1, : "POST /4-6-1.html HTTP/1.1", host: "dev2.ropon.top"

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!