linux

Linux服务器如何配置防火墙

小樊
42
2025-09-30 10:04:44
栏目: 云计算

在Linux服务器上配置防火墙通常涉及使用iptables或firewalld这样的工具。以下是使用这两种工具配置防火墙的基本步骤:

使用iptables

  1. 查看现有规则

    sudo iptables -L
    
  2. 允许特定端口: 例如,允许TCP端口80(HTTP)和443(HTTPS):

    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    
  3. 拒绝所有其他输入

    sudo iptables -P INPUT DROP
    
  4. 允许已建立的连接

    sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    
  5. 保存规则: 不同的Linux发行版可能有不同的方法来保存iptables规则。例如,在Debian/Ubuntu上:

    sudo sh -c "iptables-save > /etc/iptables/rules.v4"
    

    在CentOS/RHEL上:

    sudo service iptables save
    
  6. 重启iptables服务(如果需要):

    sudo systemctl restart iptables
    

使用firewalld

  1. 查看现有区域和规则

    sudo firewall-cmd --list-all
    
  2. 允许特定端口: 例如,允许TCP端口80和443:

    sudo firewall-cmd --permanent --add-port=80/tcp
    sudo firewall-cmd --permanent --add-port=443/tcp
    
  3. 重新加载防火墙配置

    sudo firewall-cmd --reload
    
  4. 启用防火墙(如果尚未启用):

    sudo systemctl start firewalld
    
  5. 设置防火墙开机自启

    sudo systemctl enable firewalld
    

注意事项

通过以上步骤,你可以在Linux服务器上配置基本的防火墙规则。根据具体需求,你可能需要进一步调整和优化这些规则。

0
看了该问题的人还看了