在LNMP(Linux+Nginx+MySQL+PHP)环境中配置防火墙是确保服务器安全的重要步骤。以下是详细的防火墙配置方案:
推荐使用iptables
或firewalld
(CentOS/RHEL 7+):
# 检查防火墙状态(CentOS/RHEL)
systemctl status firewalld
# 检查防火墙状态(Ubuntu/Debian)
sudo ufw status
# 启动firewalld
systemctl start firewalld
systemctl enable firewalld
# 开放必要端口
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-port=22/tcp # SSH
firewall-cmd --permanent --add-port=3306/tcp # MySQL(建议仅内网访问)
# 重新加载配置
firewall-cmd --reload
# 查看当前规则
firewall-cmd --list-all
# 清除现有规则
iptables -F
iptables -X
# 设置默认策略
iptables -P INPUT DROP
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
# 开放必要端口
iptables -A INPUT -p tcp --dport 22 -j ACCEPT # SSH
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
# 保存规则(CentOS/RHEL)
service iptables save
# 保存规则(Ubuntu/Debian)
iptables-save > /etc/iptables.rules
# 限制HTTP/HTTPS请求频率(防DDoS)
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
# 阻止恶意User-Agent
iptables -A INPUT -p tcp --dport 80 -m string --string "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" --algo bm -j DROP
# 建议MySQL仅监听内网
iptables -A INPUT -p tcp --dport 3306 -s 192.168.1.0/24 -j ACCEPT
# 或完全阻止外网访问MySQL
iptables -A INPUT -p tcp --dport 3306 -j DROP
# 阻止常见的PHP攻击模式
iptables -A INPUT -p tcp --dport 80 -m string --string "POST /wp-admin/admin-ajax.php" --algo bm -j DROP
iptables -A INPUT -p tcp --dport 80 -m string --string "eval(" --algo bm -j DROP
iptables -N ANTISCAN
iptables -A ANTISCAN -m limit --limit 5/s -j LOG --log-prefix "Port scan detected: "
iptables -A ANTISCAN -j DROP
iptables -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s -j ACCEPT
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j ANTISCAN
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j ANTISCAN
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT
iptables -A INPUT -p tcp --syn -j DROP
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT
firewall-cmd --runtime-to-permanent
# 安装iptables-persistent
apt-get install iptables-persistent
# 保存IPv4规则
netfilter-persistent save
设置定期检查防火墙日志:
# 查看防火墙日志
journalctl -u firewalld -f # firewalld
grep "iptables" /var/log/syslog # iptables
对于新手,可以考虑使用:
UFW (Ubuntu默认):
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
Fail2Ban (防暴力破解):
sudo apt-get install fail2ban
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
通过以上配置,您的LNMP环境将具备基本的安全防护能力。根据实际需求,您可以进一步调整规则。