萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

CentOS VPS 開放 80 端口完整操作指南(iptables / firewalld 兼容)

雲服務器部署 Web 服務後無法訪問,九成是 80 端口未在防火牆放行。本文提供 CentOS 6/7/8 通用的 iptables 與 firewalld 雙軌操作步驟,並包含規則持久化、驗證、常見坑點。

方案一:iptables 經典模式(CentOS 6、或 7/8 禁用 firewalld 後)

1. 添加允許規則

# 允許 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

2. 保存規則(重啟生效關鍵)

# CentOS 6
/etc/rc.d/init.d/iptables save

# CentOS 7/8 (iptables-service 包)
service iptables save
# 或
/usr/libexec/iptables/iptables.init save

3. 重啟服務應用

service iptables restart

方案二:firewalld 現代模式(CentOS 7/8 默認)

# 永久開放 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 查看

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

firewalld 查看

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

常見坑點避雷

  1. 雲廠商安全組/防火牆:AWS Security Group、阿里云安全組、騰訊云安全組需**獨立**在控制台放行 80 端口,服務器內層防火牆只是第二層。
  2. 規則順序:-I INPUT 插入到鏈首,優先於默認 DROP/REJECT 規則;若用 -A 追加可能被前置拒絕規則攔截。
  3. IPv6:同樣需放行 ip6tables 或 firewall-cmd --permanent --add-port=80/tcp(firewalld 默認雙棧)。
  4. Docker/容器:Docker 會插入自己的 iptables 鏈,可能繞過宿主機 INPUT 鏈;容器端口映射請用 -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 等正常響應,確保全鏈路通暢。

copyright © 萬盛學電腦網 all rights reserved