debian

Debian LAMP怎样配置防火墙

小樊
47
2025-03-26 22:26:11
栏目: 智能运维

在Debian系统上配置LAMP环境的同时,通常需要配置防火墙来保护服务器的安全。以下是使用iptables和ufw两种防火墙配置方法的详细步骤。

使用iptables配置防火墙

  1. 安装iptables(如果尚未安装):
sudo apt-get update
sudo apt-get install iptables
  1. 配置防火墙规则: 编辑 /etc/iptables.default.rules 文件,添加以下内容:
*filter
# Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
# Accepts all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allows all outbound traffic
-A OUTPUT -j ACCEPT
# Allows HTTP and MySQL connections from anywhere (the normal ports for websites)
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 3306 -j ACCEPT
# Allows SSH connections for script kiddies
-A INPUT -p tcp --dport 22 -j ACCEPT
# Allow ping
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
# log iptables denied calls (access via 'dmesg' command)
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
# Reject all other inbound - default deny unless explicitly allowed
-A INPUT -j REJECT
-A FORWARD -j REJECT
COMMIT
  1. 保存规则
sudo iptables-save /etc/iptables.default.rules
  1. 启用防火墙
sudo systemctl enable iptables
sudo systemctl start iptables
  1. 使防火墙规则在系统启动时自动加载: 创建 /etc/network/if-pre-up.d/iptables 文件并添加以下内容:
#!/bin/bash
/sbin/iptables-restore < /etc/iptables.default.rules

赋予执行权限:

sudo chmod +x /etc/network/if-pre-up.d/iptables

使用ufw配置防火墙

  1. 安装ufw(如果尚未安装):
sudo apt-get update
sudo apt-get install ufw
  1. 启用ufw
sudo ufw enable
  1. 允许必要的端口
sudo ufw allow 22/tcp  # 允许SSH
sudo ufw allow 80/tcp  # 允许HTTP
sudo ufw allow 443/tcp # 允许HTTPS
sudo ufw allow 3306/tcp # 允许MySQL
  1. 设置默认策略(可选):
sudo ufw default allow outgoing
sudo ufw default deny incoming
  1. 检查ufw状态
sudo ufw status verbose

以上步骤展示了如何在Debian LAMP环境中配置iptables和ufw防火墙。根据您的需求选择使用iptables或ufw,并确保在开放端口的同时考虑服务器的安全性。

0
看了该问题的人还看了