在 CentOS 上安装 Apache(httpd) 时,有几个常见但容易踩坑的点。下面按“必看 → 常见坑 → 推荐做法”给你梳理一下。
不同 CentOS 版本命令略有区别:
cat /etc/centos-release
yumdnf(兼容 yum)Apache 默认端口是 80 / 443
# 查看防火墙状态
systemctl status firewalld
# 开放端口
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
如果是云服务器,还要在 安全组 放行 80/443。
CentOS 默认开启 SELinux,常常导致:
查看状态:
getenforce
常见解决方案:
✅ 推荐(安全):
setsebool -P httpd_can_network_connect on
chcon -R -t httpd_sys_content_t /var/www/html
❌ 不推荐(仅测试):
setenforce 0
yum install httpd -y
systemctl start httpd
systemctl enable httpd
dnf install httpd -y
systemctl start httpd
systemctl enable httpd
/var/www/html/etc/httpd/conf/httpd.conf/etc/httpd/conf.d/Apache 默认用户是 apache
chown -R apache:apache /var/www/html
chmod -R 755 /var/www/html
在 /etc/httpd/conf.d/ 下新建:
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/example
<Directory /var/www/example>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
然后:
systemctl restart httpd
原因通常是:
<Directory> 没配置 Require all granted检查:
systemctl status httpd
netstat -tunlp | grep :80
journalctl -xe
✅ 启用 HTTPS(Let’s Encrypt)
dnf install certbot python3-certbot-apache
certbot --apache
✅ 隐藏版本信息
ServerTokens Prod
ServerSignature Off
✅ 禁用目录浏览
Options -Indexes
CentOS 装 Apache,最关键是:防火墙 + SELinux + 权限
如果你告诉我:
我可以给你一套更精准的配置方案。