如何有效的防刷?限制某个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;
}
...
}
- IP并发访问频率限制—-ngx_http_limit_req_module :
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指令定义了一个白名单 whiteiplist变量,默认值为1,如果客户端ip在上面的范围内, limited的值为0
map指令映射搜索引擎客户端的ip为空串,如果不是搜索引擎就显示本身真是的ip,这样搜索引擎ip就不能存到limit_req_zone内存session中,所以不会限制搜索引擎的ip访问