限制访问IP段是提高网站安全性的重要措施之一。以下是如何在Nginx中配置IP访问限制的详细方法:
location / {
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
}
location /admin {
deny 192.168.1.50;
deny 203.0.113.0/24;
allow all;
}
geo $limited {
default 0;
192.168.1.0/24 1;
10.0.0.0/8 1;
172.16.0.0/12 1;
}
server {
if ($limited) {
return 403;
}
# 其他配置...
}
location /secure {
satisfy any;
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /api {
limit_except GET POST {
allow 192.168.1.0/24;
deny all;
}
}
使用Nginx的map模块创建动态黑名单:
map $remote_addr $deny_ip {
default 0;
192.168.1.50 1;
203.0.113.100 1;
# 其他黑名单IP...
}
server {
if ($deny_ip) {
return 403;
}
# 其他配置...
}
# /etc/fail2ban/jail.local
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
白名单优于黑名单:尽可能使用allow/deny策略,默认拒绝所有,只允许已知安全的IP段
定期审查IP规则:设置日历提醒,定期审查IP限制规则
分层保护:
日志记录:确保记录被拒绝的访问尝试
log_format restricted '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" $limit_access';
测试配置:修改配置后使用nginx -t
测试语法,然后逐步重载配置
通过合理配置Nginx的IP访问限制,可以显著提高网站安全性,防止未授权访问和恶意攻击。