nginx基于$request_uri访问控制,主要匹配请求中的参数

本文详细介绍了如何在Nginx中使用$request_uri进行访问控制,通过正则表达式限制URL参数,如gid参数的长度,并展示了实际应用和403Forbidden和404NotFound的响应示例。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

运维实战课程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值