http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /api/ {
limit_req zone=one burst=20 nodelay;
# 其他配置...
}
}
}
limit_req_zone
定义共享内存区域(zone)和速率限制
$binary_remote_addr
使用客户端IP作为限制依据zone=one:10m
创建名为"one"的10MB共享内存区rate=10r/s
限制每秒10个请求limit_req
应用限制规则
burst=20
允许突发20个请求nodelay
不延迟处理突发请求,直接拒绝超限请求http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 5;
# 每个IP最多5个并发连接
}
}
}
location /admin/ {
allow 192.168.1.0/24;
allow 10.1.1.0/16;
deny all;
# 其他配置...
}
allow
允许特定IP或网段deny
拒绝访问(通常放在最后拒绝所有其他IP)location /private/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
需要创建密码文件:
htpasswd -c /etc/nginx/.htpasswd username
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
location / {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
}
location /images/ {
valid_referers none blocked example.com *.example.org;
if ($invalid_referer) {
return 403;
}
}
map $http_user_agent $blocked_agent {
default 0;
~*malicious 1;
~*spambot 1;
~*wget 1;
}
server {
if ($blocked_agent) {
return 403;
}
# 其他配置...
}
http {
# 定义限制区域
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
# 地理IP配置
geoip_country /usr/share/GeoIP/GeoIP.dat;
# 用户代理黑名单
map $http_user_agent $bad_agent {
default 0;
~*(malicious|spambot|wget) 1;
}
server {
# 基本访问控制
location /admin/ {
allow 192.168.1.0/24;
deny all;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
# API速率限制
location /api/ {
limit_req zone=api_limit burst=10 nodelay;
limit_conn conn_limit 10;
# 阻止恶意用户代理
if ($bad_agent) {
return 403;
}
}
# 国家限制
location /geo-restricted/ {
if ($geoip_country_code != US) {
return 403;
}
}
}
}
以上配置可以根据实际需求进行调整和组合使用。