Nginx提供了多种方式来限制HTTP资源请求,以下是几种常用的方法:
使用limit_req_zone
和limit_req
指令限制请求速率:
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20;
# 其他配置...
}
}
}
zone=one:10m
:创建名为"one"的共享内存区,大小为10MBrate=10r/s
:限制每秒10个请求burst=20
:允许突发20个请求使用limit_conn_zone
和limit_conn
指令限制连接数:
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 5;
# 其他配置...
}
}
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
location /api/ {
limit_except GET POST {
deny all;
}
# 其他配置...
}
location / {
if ($http_user_agent ~* (wget|curl|httrack|nikto) ) {
return 403;
}
# 其他配置...
}
location /download/ {
limit_rate 100k;
# 其他配置...
}
http {
client_max_body_size 10m;
# 其他配置...
}
需要安装ngx_http_geoip_module模块:
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default yes;
CN no;
}
server {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
以上方法可以单独使用,也可以组合使用以达到更精细的控制效果。