PHP 腳本在 CLI 執行正常,但透過瀏覽器(Apache + mod_php)訪問時回報:
Could not connect: Can't connect to MySQL server on '127.0.0.1' (13) 2003
錯誤碼 13 代表 EACCES(權限被拒),非網路不通。
CentOS 預設啟用 SELinux,限制 httpd 進程發起網路連線:
getsebool -a | grep httpd # 輸出關鍵行: httpd_can_network_connect --> off
setsebool -P httpd_can_network_connect 1
-P 參數使設定永久生效(重開機不失效)。
# 臨時關閉 setenforce 0 # 永久關閉(需重啟) vi /etc/selinux/config # SELINUX=enforcing → SELINUX=disabled
chkconfig --level 12345 iptables off chkconfig --level 12345 ip6tables off service iptables stop service ip6tables stop
setsebool -P httpd_can_network_connect 1。service httpd restart。| 指令 | 用途 |
|---|---|
/usr/sbin/sestatus -v | 詳細狀態,SELinux status: enabled 表示開啟 |
getenforce | 快速查看:Enforcing/Permissive/Disabled |
getsebool -a | grep httpd | 列出所有 httpd 相關布林值 |
httpd_can_network_connect_db:允許連接資料庫端口(3306, 5432 等)。httpd_can_sendmail:允許發送郵件。httpd_enable_cgi:允許執行 CGI 腳本。httpd_unified:統一讀寫權限(舊版相容)。CentOS 上 PHP CLI 正常但 Web 請求無法連 MySQL,90% 是 SELinux httpd_can_network_connect 為 off。使用 setsebool -P 開啟即可,既保留 SELinux 安全性又解決業務阻塞。生產環境請勿直接關閉 SELinux,應配合審計日誌分析並精準放行所需權限。