通过IP限制并发请求我们就不说了,有很多实现,今天来讲的是,当企业内网访问一个站点时,对外的IP只有一个时,这个时候限制IP地址就会误伤那些真实访问的用户了,怎么办呢,所以我们需要用cookie来识别用户,只拦截那些每秒请求达到阈值的cookie用户,其他用户就不会受影响了,当单个IP伪造的cookie数量达到我们设置的阈值时再对IP进行拦截,岂不美哉。 所以ngx_cookie_limit_req_module模块就出现了,大家不访试试,https://github.com/limithit/ngx_cookie_limit_req_module
配置极其简单nginx.conf
worker_processes 2;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#单个IP只能生成5个cookie,并且限制单个cookie每秒30个请求
cookie_limit_req_zone $http_cookie zone=two:10m rate=30r/s redis=127.0.0.1 block_second=300 cookie_max=5; #
cookie_limit_req zone=two burst=30 nodelay;
cookie_limit_req_status 403;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 403 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}