nginx单个ip访问频率限制

5,229 阅读1分钟

一、限制所有单个ip的访问频率

1、http中的配置

http {

    #$limit_conn_zone:限制并发连接数
    limit_conn_zone $binary_remote_addr zone=one1:10m;

    #limit_req_zone:请求频率
    #$binary_remote_addr:以客户端IP进行限制
    #zone=one:10m:创建IP存储区大小为10M,用来存储访问频率
    #rate=10r/s:表示客户端的访问评率为每秒10次
    limit_req_zone $binary_remote_addr zone=one2:10m   rate=10r/s;
     
}    

2、server配置

server {
        listen       80;
        server_name  localhost;
       

        location / {
            #限制并发数2
            limit_conn  one1  2;  
            #burst:如果请求的频率超过了限制域配置的值,请求处理会被延迟
            #nodelay:超过频率限制的请求会被延迟,直到被延迟的请求数超过了定义的阈值,这个请求会被终止,并返回503
            limit_req   zone=one2 burst=10 nodelay;
            root   html;
            index  index.html index.htm;
        }

}

二、访问白名单的配置

1、http中的配置

http {
# geo:指令定义了一个白名单$limited变量,默认值为1,如果客户端ip在上面的范围内,$limited的值为0
    geo $limited{
        default 1;
        10.0.0.140 0;  #把10.0.0.140设置为白名单
        10.0.0.141 0;  #白名单ip,可继续添加
    }
    #使用map指令映射搜索引擎客户端的ip为空串,如果不是搜索引擎就显示本身真是的ip
    #这样搜索引擎ip就不能存到limit_req_zone内存session中,所以不会限制搜索引擎的ip访问

    map $limited $limit {    
        1 $binary_remote_addr;   
        0 "";    
    }  
    limit_conn_zone $limit zone=one:20m;
    limit_req_zone $limit zone=one2:20m   rate=10r/s; 
}

2、server配置

server {
        listen       80;
        server_name  localhost;
       

        location / {
            limit_conn  one  2;   
            limit_req   zone=one2 burst=10 nodelay; 
            root   html;
            index  index.html index.htm;
        }

}