Nginx提供了多种方式来限制访问,包括基于IP的限制、连接数限制和请求速率限制等。以下是几种常见的访问限制配置方法:
location /admin/ {
allow 192.168.1.100; # 允许的IP
allow 10.0.0.0/24; # 允许的IP段
deny all; # 拒绝其他所有IP
}
location / {
deny 192.168.1.1; # 拒绝特定IP
deny 123.45.67.89; # 拒绝另一个IP
allow all; # 允许其他所有IP
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location /search/ {
limit_req zone=one burst=5;
}
}
}
10m
:共享内存区域大小rate=1r/s
:每秒1个请求burst=5
:允许突发5个请求http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 1; # 每个IP最多1个连接
}
}
}
location /private/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
需要创建.htpasswd
文件:
htpasswd -c /etc/nginx/.htpasswd username
需要安装ngx_http_geoip_module
模块:
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
if ($allowed_country = no) {
return 403;
}
}
}
location /api/ {
if ($request_method !~ ^(GET|POST)$ ) {
return 405;
}
}
location / {
if ($http_user_agent ~* (wget|curl|libwww-perl)) {
return 403;
}
}
limit_req_status
和limit_conn_status
自定义返回状态码配置完成后,记得测试并重新加载Nginx配置:
nginx -t && nginx -s reload