在 CentOS 上适配/使用 Apache(httpd),通常包含 安装、配置、端口/防火墙、SELinux、虚拟主机、性能优化 等几个关键环节。下面按 CentOS 7 / CentOS 8 / Rocky / Alma 通用 的方式说明。
yum install -y httpd
dnf install -y httpd
systemctl start httpd
systemctl enable httpd
查看状态:
systemctl status httpd
CentOS 默认使用 firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
验证:
firewall-cmd --list-services
getenforce
Enforcing:需要配置Permissive:仅记录Disabled:不生效(不推荐)setsebool -P httpd_can_network_connect 1
Apache 默认只能访问:
/var/www/html
如果你使用自定义目录(如 /data/www):
semanage fcontext -a -t httpd_sys_content_t "/data/www(/.*)?"
restorecon -Rv /data/www
| 路径 | 说明 |
|---|---|
/etc/httpd/ |
主配置目录 |
/etc/httpd/conf/httpd.conf |
主配置文件 |
/etc/httpd/conf.d/ |
额外配置 |
/var/www/html/ |
默认网站根目录 |
/var/log/httpd/ |
日志目录 |
vim /etc/httpd/conf.d/example.conf
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/example
<Directory "/var/www/example">
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/example-error.log
CustomLog /var/log/httpd/example-access.log combined
</VirtualHost>
创建目录:
mkdir -p /var/www/example
echo "Hello Apache" > /var/www/example/index.html
重启 Apache:
systemctl restart httpd
yum install -y php php-cli php-common
dnf install -y php php-cli php-common
测试:
echo "<?php phpinfo(); ?>" > /var/www/html/info.php
访问:
http://服务器IP/info.php
✅ 检查:
Require all granted✅ 检查:
ss -lntp | grep httpd
httpd -t
# 关闭目录浏览
Options -Indexes
# 隐藏版本信息
ServerTokens Prod
ServerSignature Off
CentOS 适配 Apache 的核心 = 安装 + 防火墙 + SELinux + 目录权限 + 虚拟主机配置
如果你愿意,我可以:
直接告诉我你的 CentOS 版本 + 使用场景 即可。