nginx之限制用户的访问

我们经常会遇到这种情况,服务器流量异常,负载过大等等。
对于大流量恶意的攻击访问,会带来带宽的浪费,服务器压力,影响业务,往往考虑对同一个IP的连接数,并发数进行限制。

1. 限制并发

(1)vim /usr/local/nginx/conf/nginx.conf

#gzip  on;
    limit_conn_zone $binary_remote_addr zone=addr:10m;
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

其中,limit_conn_zone 用来限制同一时间连接数,即并发限制。

limit_req_zone 用来限制单位时间内的请求数,即速率限制,采用的“漏桶算法” “leaky bucket”

$binary_remote_addr:是限制同一客户端IP地址。
one=one:10m:表示生成一个大小为10M,名字为one的内存区域,用来存储访问的频次信息。

定义一个名为addr的limit_conn_zone
$binary_remote_addr:是限制同一客户端IP地址

location /download {
           limit_conn addr 1; #只能一个并发,多了会报错
}
[root@server1 ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@server1 ~]# nginx 
[root@server1 ~]# mkdir /usr/local/nginx/html/download
[root@server1 ~]# cd/usr/local/nginx/html/download
-bash: cd/usr/local/nginx/html/download: No such file or directory
[root@server1 ~]# cd /usr/local/nginx/html/download
[root@server1 download]# ls
[root@server1 download]# mv /opt/demo/a.png .
[root@server1 download]# ls
a.png
[root@server1 download]# 

在这里插入图片描述清空server1的access.log

[root@server1 ~]# cd /usr/local/nginx/logs/
[root@server1 logs]# ls
2020-02-25_access.log  access.log  error.log  nginx.pid
[root@server1 logs]# > access.log 
[root@server1 logs]# cat access.log 
[root@server1 logs]# 

客户端并发1000个请求测试:

[kiosk@foundation8 ~]$ ab -c 10 -n 1000 http://172.25.254.1/download/a.png
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.25.254.1 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

在这里插入图片描述查看server1的access.log
可以发现除了有少量的200状态码,更多的是503。

2. 限制带宽

limit_rate 50k;  #限制带宽,每秒最多50k
[root@server1 logs]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@server1 logs]# nginx -s reload

可以发现,客户端测试时请求时间明显加长。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值