Nginx根据IP限制访问

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

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

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

http{

##取用户的真实IP

 map $http_x_forwarded_for  $clientRealIp {
        ## 没有通过代理,直接用 remote_addr
        ""      $remote_addr;
        ## 用正则匹配,从 x_forwarded_for 中取得用户的原始IP ## 例如 X-Forwarded-For: 202.123.123.11, 208.22.22.234, 192.168.2.100,...## 这里第一个 202.123.123.11 是用户的真实IP,后面其它都是经过的 CDN 服务器
        ~^(?P<firstAddr>[0-9\.]+),?.*$  $firstAddr;
    }
        ## 通过 map 指令,我们为 nginx 创建了一个变量 $clientRealIp ,这个就是 原始用户的真实 IP 地址,## 不论用户是直接访问,还是通过一串 CDN 之后的访问,我们都能取得正确的原始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;
      }

}

更多Nginx相关教程见以下内容

Nginx 的详细介绍请点这里
Nginx 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2016-11/136619.htm