nginx根据IP限制访问

nginx有两个模块可以控制访问

HttpLimitZoneModule    限制同时并发访问的数量

HttpLimitReqModule     限制访问数据,每秒内最多几个请求

http{

 ##白名单,在此的ip将不会限速,0值为不限制
     geo $whitelist  {
         default 1;
         127.0.0.1 0;
         192.168.0.1/32 0;
     }

 map $whitelist $clientRealIp {
        1     $binary_remote_addr;

         0    '';;#ip为0时设置为空值,limit_conn_zone和limit_req_zone指令对于键为空值的将会被忽略,从而实现对于列出来的IP不做限制
           }
      

    ## 每秒并发连接限制
    limit_conn_zone $clientRealIp zone=TotalConnLimitZone:10m ; ##1M大概可以保存16000IP
    limit_conn  TotalConnLimitZone  10;##每个IP最多有10个并发连接
    limit_conn_log_level notice;
    ## 每秒请求数限制
    limit_req_zone $clientRealIp zone=ConnLimitZone:10m  rate=10r/s;
    limit_req_log_level notice;

}

server{

  listen       80;

  location ~ .*.(php|php5)?$
       {
          limit_req   zone=ConnLimitZone  burst=5 nodelay; #每秒处理 10 个请求 + 5个排队,超过直接返回503
          fastcgi_pass  127.0.0.1:9000;
          fastcgi_index index.php;
          include fastcgi.conf;
          fastcgi_connect_timeout 300s;
          fastcgi_read_timeout 300s;
       }

}

原文地址:https://www.cnblogs.com/latma/p/6018639.html