基于用户行为的访问控制列表(ACL)是Nginx反向代理中实现精细化访问控制的有效方式。以下是详细的配置方法和策略:
# 在http块中定义限制区域
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location / {
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://backend;
# 超过频率限制返回429状态码
error_page 429 = @toomanyrequests;
}
location @toomanyrequests {
return 429 "Too Many Requests";
}
}
# 阻止特定User-Agent
map $http_user_agent $bad_agent {
default 0;
"~*bot" 1;
"~*spider" 1;
"~*scan" 1;
}
server {
if ($bad_agent) {
return 403;
}
# 阻止POST方法到特定路径
location /api {
limit_except GET {
deny all;
}
proxy_pass http://backend;
}
}
# 需要GeoIP模块
geo $block_country {
default 0;
CN 1; # 允许中国
US 1; # 允许美国
# 其他地区默认拒绝
}
server {
if ($block_country = 0) {
return 403;
}
proxy_pass http://backend;
}
# 使用Lua脚本检测异常行为
location / {
access_by_lua_block {
local requests = tonumber(ngx.var.connections_requests) or 0
if requests > 100 then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
proxy_pass http://backend;
}
# 使用Nginx+Lua实现动态黑名单
http {
lua_shared_dict ip_blacklist 10m;
init_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
blacklist:set("1.2.3.4", true) # 静态黑名单
}
server {
location / {
access_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
if blacklist:get(ngx.var.remote_addr) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
proxy_pass http://backend;
}
# 动态添加黑名单的API端点(需保护)
location /admin/blacklist {
allow 192.168.1.0/24;
deny all;
content_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
local ip = ngx.var.arg_ip
if ip then
blacklist:set(ip, true)
ngx.say("Added "..ip.." to blacklist")
end
}
}
}
}
# 限制非工作时间访问
map $time_iso8601 $is_worktime {
default 0;
"~*T(09|10|11|12|13|14|15|16|17):" 1;
}
server {
location / {
if ($is_worktime = 0) {
return 403 "Service available only during work hours (09:00-18:00)";
}
proxy_pass http://backend;
}
}
通过以上配置,可以构建一个基于用户行为的精细化访问控制系统,有效保护后端服务免受恶意请求和异常访问的影响。