雲服務器部署 Web 服務後無法訪問,九成是 80 端口未在防火牆放行。本文提供 CentOS 6/7/8 通用的 iptables 與 firewalld 雙軌操作步驟,並包含規則持久化、驗證、常見坑點。
# 允許 TCP 80 端口(HTTP)
/sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
# 同步放行 SSH 22 端口,防止誤鎖自己
/sbin/iptables -I INPUT -p tcp --dport 22 -j ACCEPT
# CentOS 6
/etc/rc.d/init.d/iptables save
# CentOS 7/8 (iptables-service 包)
service iptables save
# 或
/usr/libexec/iptables/iptables.init save
service iptables restart
# 永久開放 80/tcp
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --permanent --add-port=22/tcp # 確保 SSH
# 重新載入生效
firewall-cmd --reload
# 查看已開放端口
firewall-cmd --list-ports
iptables -nL INPUT --line-numbers | grep -E '80|22'
# 輸出示例:
# 1 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
# 2 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
firewall-cmd --list-all
# 本機
ss -lntp | grep :80
netstat -lntp | grep :80
# 遠程測試
telnet YOUR_SERVER_IP 80
nc -zv YOUR_SERVER_IP 80
curl -I https://YOUR_SERVER_IP
-I INPUT 插入到鏈首,優先於默認 DROP/REJECT 規則;若用 -A 追加可能被前置拒絕規則攔截。ip6tables 或 firewall-cmd --permanent --add-port=80/tcp(firewalld 默認雙棧)。-p 80:80 而非依賴宿主機防火牆。#!/bin/bash
# open_port_80.sh
set -e
if command -v firewall-cmd &>/dev/null && systemctl is-active firewalld &>/dev/null; then
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload
echo "firewalld: 80/tcp opened"
else
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp --dport 22 -j ACCEPT
service iptables save 2>/dev/null || /etc/rc.d/init.d/iptables save
service iptables restart
echo "iptables: 80/tcp opened"
fi
執行完畢後,務必從**外部客戶端**驗證 curl -I https://IP 返回 200/301/302 等正常響應,確保全鏈路通暢。