location / {
# 允许特定IP访问
allow 192.168.1.1;
allow 192.168.1.0/24;
# 拒绝其他所有IP
deny all;
# 默认处理
proxy_pass http://backend;
}
location /admin {
auth_basic "Administrator's Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
创建密码文件:
htpasswd -c /etc/nginx/.htpasswd username
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
if ($http_user_agent ~* (wget|curl|python|java)) {
return 403;
}
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /download/ {
limit_conn addr 1; # 每个IP同时只能有1个连接
}
}
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /api/ {
limit_req zone=one burst=20 nodelay;
# 平均速率10请求/秒,突发允许20请求
}
}
}
location /download/ {
limit_rate 100k; # 限制下载速度为100KB/s
limit_rate_after 1m; # 下载1MB后开始限速
}
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;
}
}
}
http {
# 创建共享内存区域存储黑名单IP
lua_shared_dict ip_blacklist 10m;
server {
location / {
access_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
local client_ip = ngx.var.remote_addr
if blacklist:get(client_ip) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
}
location /blacklist {
content_by_lua_block {
-- 通过API动态添加IP到黑名单
local blacklist = ngx.shared.ip_blacklist
local ip = ngx.var.arg_ip
blacklist:set(ip, true, 3600) -- 黑名单1小时
ngx.say("Added "..ip.." to blacklist")
}
}
}
}
以上配置可根据实际需求组合使用,构建适合您应用场景的安全访问控制体系。