温馨提示×

Linux防火墙如何保护Web服务器

小樊
47
2025-08-03 10:23:58
栏目: 云计算

Linux 防火墙是保护 Web 服务器安全的重要工具,可以通过配置防火墙规则来限制对 Web 服务器的访问,防止未经授权的访问和恶意攻击。以下是使用 Linux 防火墙保护 Web 服务器的一些基本步骤和示例:

选择合适的防火墙工具

  • iptables:传统 Linux 防火墙工具,直接操作内核的 Netfilter 框架,适合手动配置复杂规则。
  • ufw(Uncomplicated Firewall):为 iptables 提供简化接口,适合新手和快速配置。
  • firewalld:RHEL/CentOS/Fedora 的默认动态防火墙管理工具,支持“区域”概念,适合服务器多网卡场景。
  • nftables:iptables 的替代品,语法更简洁,性能更好。

配置防火墙规则

  • 启用防火墙

    # 对于使用 ufw 的系统(如 Ubuntu)
    sudo ufw enable
    
    # 对于使用 firewalld 的系统(如 CentOS)
    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  • 开放 Web 服务器端口

    # 使用 ufw 开放 HTTP 和 HTTPS 端口
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    
    # 使用 firewalld 开放 HTTP 和 HTTPS 端口
    sudo firewall-cmd --zone=public --add-service=http --permanent
    sudo firewall-cmd --zone=public --add-service=https --permanent
    sudo firewall-cmd --reload
    
  • 限制访问来源

    # 允许特定 IP 访问 Web 服务器
    sudo ufw allow from 192.168.1.100 to any port 80
    
    # 使用 firewalld 允许特定 IP 访问 Web 服务器
    sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="http" accept'
    sudo firewall-cmd --reload
    
  • 防止 DDoS 攻击

    # 限制某个 IP 的连接频率,防止频繁的请求导致服务器瘫痪
    sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="http" limit value="50/m" accept'
    sudo firewall-cmd --reload
    

防火墙规则备份与还原

  • 在进行大规模修改前备份防火墙规则,以防止误操作导致配置出错。

    # 备份 firewalld 规则
    sudo firewall-cmd --runtime-to-permanent
    
    # 备份 ufw 规则
    sudo cp /etc/ufw/ufw.conf /etc/ufw/ufw.conf.backup
    

通过上述步骤,可以有效地配置 Linux 防火墙来保护 Web 服务器。具体的配置方法可能会根据所使用的 Linux 发行版和防火墙工具有所不同,建议参考相应的官方文档进行操作。

0