企业实战-Nginx限制用户的访问

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

限制并发

1.修改配置文件nginx.conf文件
添加34,35行内容,和54-57行内容

[root@server1 conf]# vim nginx.conf

 33     #gzip  on;
 34     limit_conn_zone $binary_remote_addr zone=addr:10m;
 35     limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;			#注意:必须写在server上面
 36     server {
 ......
 54         location /download {
 55             limit_conn addr 1;  #只能一个并发,多了会报错
 56             #limit_rate 50k;    #限制带宽,每秒最多50k
 57         }

其中:
limit_conn_zone $binary_remote_addr zone=addr:10m; 表示大小是10m内存 10m的内存来对IP传输开销
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; 1s不超过一个请求
limit_conn_zone 用来限制同一时间连接数,即并发限制
limit_req_zone 用来限制单位时间的请求数,即速率限制,采用漏桶算法
$binary_remote_addr 是限制同一客户端ip地址
zone=addr:10m 表示生成一个大小为10m,名字为one的内存区域,用来存储访问的频次信息
重新加载nginx:

[root@server1 conf]# 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 conf]# nginx -s reload

2.测试

新建download目录后放入测试文件:

[root@server1 conf]# mkdir /usr/local/nginx/html/download
[root@server1 conf]# cd /usr/local/nginx/html/download
[root@server1 download]# ls
1.jpg

清空日志文件:

[root@server1 download]# cd /usr/local/nginx/logs
[root@server1 logs]# >access.log 
[root@server1 logs]# cat access.log 

测试后查看日志可以发现好多503错误,即服务器对并发进行了限制

2.限制带宽

带宽限制的测试即只有配置文件不相同

[root@server1 conf]# vim nginx.conf

 33     #gzip  on;
 34     limit_conn_zone $binary_remote_addr zone=addr:10m;
 35     limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;			#注意:必须写在server上面
 36     server {
 ......
 54         location /download {
 55             #limit_conn addr 1;  #只能一个并发,多了会报错
 56 
 57             limit_rate 50k;    #限制带宽,每秒最多50k
 58         }

最后进行客户端测试时发现速度明显变慢,即服务器对速度进行了限制。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值