Nginx模块(upstream和ngx_http_limit_req_module)使用

如何有效的防刷?限制某个IP某一时间段的访问次数是一个让人头疼的问题,起初有同事说自己写LUA脚本进行控制,后面再Nginx网上找到对应的模块


  • 负载均衡—-upstream :
http {
    upstream webserver {
     ip_hash;
     server   192.168.254.1:8080     weight=1  max_fails=2 fail_timeout=30s;
     server   192.168.254.2:8080     weight=3  max_fails=2 fail_timeout=30s;
     server   192.168.254.3:8080     weight=3  max_fails=2 fail_timeout=30s;
    }
    ...
}
http {
    #定义一个名为abc的limit_req_zone用来存储session,大小是10M内存,
    #以$binary_remote_addr 为key,限制平均每秒的请求为15个,
    limit_req_zone $binary_remote_addr zone=abc:10m rate=15r/s;#这里abc
    ...
    server {
        ...
        location /search/ {
            limit_req zone=abc burst=5;#这里abc
        }
}

值得注意:

A client IP address serves as a key. Note that instead of remoteaddr,the binary_remote_addr variable is used here. The $binary_remote_addr variable’s size is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses. The stored state always occupies 64 bytes on 32-bit platforms and 128 bytes on 64-bit platforms. One megabyte zone can keep about 16 thousand 64-byte states or about 8 thousand 128-byte states. If the zone storage is exhausted, the server will return the 503 (Service Temporarily Unavailable) error to all further requests.

  • 限制排除白名单—-geo & map:
http {
   ...

    geo $whiteiplist {
        default 1;
        #google 
        64.233.160.0/19 0;
        65.52.0.0/14 0;
        #MyIPs
         192.247.112.82 0;
         192.206.176.238 0;
         127.0.0.1 0;
     }

    map $whiteiplist   $limit {
        1 $binary_remote_addr;
        0 "";
    }
    ...
}    

geo指令定义了一个白名单 whiteiplist1ip limited的值为0

map指令映射搜索引擎客户端的ip为空串,如果不是搜索引擎就显示本身真是的ip,这样搜索引擎ip就不能存到limit_req_zone内存session中,所以不会限制搜索引擎的ip访问

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值