配置LNMP(Linux, Nginx, MySQL/MariaDB, PHP)服务器的防火墙是确保服务器安全的重要步骤。以下是几种常见的防火墙配置方法,具体取决于你使用的Linux发行版。
firewalld
配置防火墙(推荐用于CentOS/RHEL 7+)安装和启用 firewalld
(如果尚未安装):
sudo systemctl start firewalld
sudo systemctl enable firewalld
开放必要端口:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-port=22/tcp # SSH
sudo firewall-cmd --permanent --add-port=3306/tcp # MySQL(建议仅内网访问)
重新加载配置:
sudo firewall-cmd --reload
查看当前规则:
sudo firewall-cmd --list-all
ufw
配置防火墙(适用于Ubuntu/Debian)安装和启用 ufw
(如果尚未安装):
sudo apt update
sudo apt install ufw
配置 ufw
规则:
sudo ufw allow 80/tcp # Nginx HTTP
sudo ufw allow 443/tcp # Nginx HTTPS
sudo ufw allow 3306/tcp # MySQL
sudo ufw allow 22/tcp # SSH(建议限制访问)
查看 ufw
状态:
sudo ufw status
重新加载 ufw
配置(如果修改了规则):
sudo ufw reload
设置默认策略:
iptables
:sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
ufw
,默认策略已启用。允许已建立的连接:
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
允许本地回环接口流量:
sudo iptables -A INPUT -i lo -j ACCEPT
保存规则:
iptables
:sudo iptables-save > /etc/sysconfig/iptables
ufw
,规则会自动保存。限制HTTP/HTTPS请求频率(防DDoS):
sudo iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
阻止恶意User-Agent:
sudo 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安全:
sudo iptables -A INPUT -p tcp --dport 3306 -s 192.168.1.0/24 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 3306 -j DROP
PHP安全:
sudo iptables -A INPUT -p tcp --dport 80 -m string --string "POST /wp-admin/admin-ajax.php" --algo bm -j DROP
sudo iptables -A INPUT -p tcp --dport 80 -m string --string "eval(" --algo bm -j DROP
请根据你的具体需求和操作系统选择合适的防火墙配置方法,并在生产环境中进行充分测试。定期检查和更新防火墙规则是确保服务器安全的关键。