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地址
## 这里取得原始用户的IP地址
map $http_x_forwarded_for $clientRealIp {
"" $remote_addr;
~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr;
}
## 针对原始用户 IP 地址做限制
limit_conn_zone $clientRealIp zone=TotalConnLimitZone:20m;
limit_conn TotalConnLimitZone 50;
limit_conn_log_level notice;
## 针对原始用户 IP 地址做限制
limit_req_zone $clientRealIpzone=ConnLimitZone:20m rate=10r/s;
#limit_req zone=ConnLimitZone burst=10 nodelay;
limit_req_log_level notice;
## 具体服务器配置
server {
listen 80;
location ~ \.php$ {
##最多 5 个排队, 由于每秒处理10 个请求 + 5个排队,你一秒最多发送 15 个请求过来,再多就直接返回 503 错误给你了
limit_reqzone=ConnLimitZone burst=5 nodelay;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
b)limit_reqzone=one burst=10 nodelay;
i.添加nodelay配置,这样就是根据你的网络状况访问,一分钟访问够10次后,服务器直接返回503。
ii.Eg:imit_req_zone$binary_remote_addrzone=one:100m rate=10r/m;
就是每分钟有10个令牌供用户使用,按照b的配置情况,就会根据网络情况访问url,如果一分钟超过10个令牌,服务器返回503,等待下一个一分钟领取访问令牌。
http{
map $http_x_forwarded_for $clientRealIp {
""$remote_addr;
~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr;
}
limit_req_status 599;
limit_req_zone$clientRealIp zone=allips:70m rate=20r/s;
limit_req_log_level notice;
}
Server {
Location / {
limit_req zone=allips burst=5 nodelay;
}