前言
对于一些自己建站的人来说(最常见的就是搭建自己的私人博客),可能会不希望中国方向的访问(总会有些内容不希望中国用户看到),此时屏蔽中国IP的访问就显得格外重要了。
这里介绍如何使用iptables实现系统级的屏蔽中国大陆 IP 对 80 和 443 端口的访问。
原理概述
iptables 本身并不知道“哪个 IP 属于中国”,因此需要借助 IP 地址段数据。常用来源包括:
- IPip.net
- APNIC 分配表
- https://github.com/17mon/china_ip_list
- 或者使用 ipset 提高效率
如果你直接用 iptables 加上上万条规则,系统性能会崩。所以正确做法是:ipset + iptables 配合使用。
ipset + I-tables
1. 安装必要组件
sudo apt update
sudo apt install ipset iptables -y
2. 使用ipset创建 IP 集合
sudo ipset create china hash:net
3. 下载中国 IP 段列表
wget -O /tmp/china_ip_list.txt https://raw.githubusercontent.com/17mon/china_ip_list/master/china_ip_list.txt
4.导入到 ipset
while read ip; do
sudo ipset add china $ip
done < /tmp/china_ip_list.txt
5.设置 iptables 规则:阻止 china 集合访问 80/443
sudo iptables -I INPUT -p tcp -m multiport --dports 80,443 -m set --match-set china src -j DROP
保存配置
1. 保存 ipset
sudo ipset save > /etc/ipset.conf
2. 保存 iptables
sudo sh -c 'iptables-save > /etc/iptables/rules.v4'
3. 开机自动加载
编辑 /etc/rc.local(如果不存在就创建):
#!/bin/bash
ipset restore < /etc/ipset.conf
iptables-restore < /etc/iptables/rules.v4
exit 0
给它执行权限:
sudo chmod +x /etc/rc.local
后记
-
若你的服务器跑 nginx / caddy / apache,可在应用层使用 GeoIP 模块实现更灵活的控制(例如允许部分地区访问)。
-
若想屏蔽中国以外的 IP(“只允许中国访问”),可把规则反转为 -j ACCEPT 并加一条默认 DROP。
-
若希望规则更自动化,可用定时任务更新:
crontab -e @weekly wget -O /tmp/china_ip_list.txt https://raw.githubusercontent.com/17mon/china_ip_list/master/china_ip_list.txt && \ ipset flush china && while read ip; do ipset add china $ip; done < /tmp/china_ip_list.txt
CF 直接地区阻止 方便多了
bd
@Maureen #1 但得开小黄云才行
我顶
又学到一手
感谢分享
cf直接全胖了