必须在location块内按“先allow后deny all”顺序配置白名单规则,且需通过set_real_ip_from和real_ip_header还原真实IP;写在http/server顶层或if块中均不生效。

要限制管理系统admin入口仅被可信IP访问,必须在应用层或网络层拦截非白名单请求,不能依赖登录后验证——否则暴力破解和扫描器已能触达登录页。
用Nginx在location块中配置IP白名单
这是最常用、最直接的方案,规则生效快且不依赖系统防火墙,适合所有部署Nginx作为反向代理的后台系统。
第一步:打开Nginx主配置文件或站点配置文件,定位到管理后台对应的location块,例如:location /admin { 或 location ^~ /wp-admin {。
第二步:在该location块内,先写allow,再写deny all,顺序不可颠倒。单个IP写成allow 203.123.45.67;,CIDR段写成allow 192.168.10.0/24;。
第三步:在所有allow语句之后,添加deny all;。这一步漏掉就等于没设白名单。
第四步:执行nginx -t检查语法,无报错后运行nginx -s reload重载配置。此时非白名单IP访问/admin路径会立即返回403 Forbidden。
注意:如果服务器前端有SLB、CDN或WAF,$remote_addr拿到的是代理IP而非真实客户端IP。必须先配置set_real_ip_from并启用real_ip_header,否则白名单完全失效。
用iptables在系统层拦截admin端口流量
适用于admin服务直接监听在特定端口(如8080、9001)且未经过Nginx代理的场景,拦截更早、更彻底。
方法一:只放行指定IP访问该端口
iptables -I INPUT -p tcp --dport 8080 -s 203.123.45.67 -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -j DROP
方法二:先设默认策略为DROP,再逐条放行
iptables -P INPUT DROP
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -s 203.123.45.67 -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -s 192.168.5.0/24 -j ACCEPT
【关键】必须用-I插入ACCEPT规则到INPUT链最前面,否则DROP规则先匹配,放行规则永不生效。
保存规则:CentOS/RHEL执行service iptables save;Ubuntu/Debian执行iptables-save > /etc/iptables/rules.v4。
用firewalld富规则精确控制admin服务访问
firewalld不支持“全局只开admin端口”,必须用rich rule绑定IP+端口+协议三要素,否则规则会被绕过。
先确认firewalld已启用:systemctl is-active firewalld。若为inactive,运行systemctl start firewalld && systemctl enable firewalld。
执行以下命令添加白名单(以admin服务监听在TCP 9001端口为例):
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.123.45.67" port port="9001" protocol="tcp" accept'
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="2001:db8::1" port port="9001" protocol="tcp" accept'
如果之前已用--add-port=9001/tcp全局开放过该端口,必须先删除:firewall-cmd --permanent --remove-port=9001/tcp,否则rich rule不会触发。
最后执行firewall-cmd --reload使规则生效。
用ipset管理大量白名单IP提升iptables性能
当白名单IP超过20个,或需频繁增删时,用普通iptables追加规则会导致匹配变慢;ipset将IP集合哈希化,查表时间恒定。
创建名为admin_whitelist的hash:ip集合:ipset create admin_whitelist hash:ip。
批量导入IP列表(假设IP存于/opt/admin-whitelist.txt,每行一个IP):while read ip; do ipset add admin_whitelist "$ip"; done 。
在iptables中引用该集合:iptables -I INPUT -p tcp --dport 9001 -m set --match-set admin_whitelist src -j ACCEPT。
iptables -A INPUT -p tcp --dport 9001 -j DROP。
保存ipset规则(CentOS/RHEL):ipset save admin_whitelist > /etc/sysconfig/ipset-admin-whitelist;开机自动加载需配置systemd服务或rc.local。

















