zh
VPS防火墙设置:UFW和iptables完整配置指南
防火墙是服务器安全的第一道防线,它控制哪些网络流量可以进出您的服务器。未配置防火墙的VPS相当于一栋没有门锁的房子,任何人都可以尝试访问所有端口。本指南介绍两种主流方案:UFW(适合初学者)和iptables(适合高级用户)。
Need this done for your project?
We implement, you ship. Async, documented, done in days.
使用UFW快速配置防火墙(推荐初学者)
UFW(Uncomplicated Firewall)是Ubuntu/Debian系统上iptables的前端工具,语法简洁直观。
安装UFW(Ubuntu通常已预装):
apt install ufw -y
配置基础规则(操作前务必确保SSH端口已开放,否则会锁死自己):
允许SSH连接(默认端口22):
ufw allow 22/tcp
若已将SSH改为自定义端口,如50022:
ufw allow 50022/tcp
开放Web服务端口:
ufw allow 80/tcp
ufw allow 443/tcp
启用防火墙(默认拒绝所有入站,允许所有出站):
ufw enable
查看当前规则:
ufw status verbose
删除规则:
ufw delete allow 80/tcp
UFW高级配置:限速和IP白名单
UFW还支持一些实用的高级功能。
限制SSH登录频率(防止暴力破解):
ufw limit ssh
限速规则:同一IP 30秒内尝试超过6次连接会被临时封禁。
允许特定IP访问所有端口(白名单):
ufw allow from 123.456.789.0
允许特定IP访问指定端口:
ufw allow from 123.456.789.0 to any port 3306
拒绝特定IP(黑名单):
ufw deny from 恶意IP
按网段设置规则:
ufw allow from 10.0.0.0/8
查看规则编号(用于删除特定规则):
ufw status numbered
ufw delete 规则编号
iptables基础配置(高级用户)
iptables是Linux内核级别的包过滤工具,功能最强大但语法较复杂。以下是一套基础规则模板:
清除现有规则:
iptables -F
iptables -X
设置默认策略(先开放,配置完成后再收紧):
iptables -P INPUT ACCEPT
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
允许已建立的连接:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
允许本地回环:
iptables -A INPUT -i lo -j ACCEPT
允许SSH(自定义端口50022):
iptables -A INPUT -p tcp --dport 50022 -j ACCEPT
允许HTTP/HTTPS:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
拒绝其他所有入站:
iptables -P INPUT DROP
保存规则(Ubuntu/Debian):
apt install iptables-persistent -y
netfilter-persistent save
Related Services
Why Anubiz Host
100% async — no calls, no meetings
Delivered in days, not weeks
Full documentation included
Production-grade from day one
Security-first approach
Post-delivery support included
Ready to get started?
Skip the research. Tell us what you need, and we'll scope it, implement it, and hand it back — fully documented and production-ready.