nginx基于$request_uri访问控制,主要匹配请求中的参数
1).$request_uri访问控制功能:
$request_uri比$docuemnt_uri多了请求的参数。主要是针对请求的uri中的参数进行控制。
2).$request_uri访问控制示例:
案例:
if ($request_uri ~ "gid=\d{9,12}")
{
return 403;
}
说明:\d{9,12}是正则表达式,表示9到12个数字,例如gid=1234567890就符合要求。
测试链接:
1. www.1.com/index.php?gid=1234567890&pid=111 匹配
2. www.1.com/gid=123 不匹配
或者案例:
if ($request_uri ~ "admin.php\?gid=\d{9,12}")
{
return 403;
}
说明:\d{9,12}是正则表达式,表示9到12个数字,例如gid=1234567890就符合要求。
背景知识:
曾经有一个客户的网站cc攻击,对方发起太多类似这样的请求:/read-123405150-1.html
实际上,这样的请求并不是正常的请求,网站会抛出一个页面,提示帖子不存在。
所以,可以直接针对这样的请求,return 404状态码。
相关配置如下:
if ($request_uri ~ "/\d{7,11}-1.html") {return 404;}
if ($request_uri ~ "/\d{7,11}.html") {return 404;}
看到的nginx的日志拒绝结果:
… “GET 、738771793-1.html HTTP/1.1” 404 …
3).$request_uri访问控制示例详解:
[root@localhost ~]# cat /usr/local/nginx/conf/vhost/www.1.conf
server{
listen 80;
server_name www.1.com;
root /data/wwwroot/www.1.com;
index index.html;
if ($request_uri ~ "gid=\d{9,12}")
{
return 403;
}
}
[root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload
匹配:
[root@localhost ~]# curl www.1.com/index.php?gid=1234567890&pid=111
[1] 32477
[root@localhost ~]# <html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@localhost ~]# curl www.1.com/index.php?gid=1234567890
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
不匹配:
[root@localhost ~]# curl www.1.com/index.php?gid=123&pid=111
[1] 32503
[root@localhost ~]# <html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@localhost ~]# curl www.1.com/gid=123
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@localhost ~]# curl www.1.com/index.php?gid=12x345678990
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
$request_uri访问控制参考链接:
https://github.com/aminglinux/nginx/blob/master/access/request_uri.md
本文详细介绍了如何在Nginx中使用$request_uri进行访问控制,通过正则表达式限制URL参数,如gid参数的长度,并展示了实际应用和403Forbidden和404NotFound的响应示例。
1418

被折叠的 条评论
为什么被折叠?



