下面按**“在 CentOS 上安装、配置、优化 Apache(httpd)”**的思路,系统说明 Apache 如何适配 CentOS,适合生产环境使用。
# CentOS 7 / 8
yum install -y httpd
或(CentOS 8+):
dnf install -y httpd
systemctl start httpd
systemctl enable httpd
查看状态:
systemctl status httpd
| 作用 | 路径 |
|---|---|
| 主配置文件 | /etc/httpd/conf/httpd.conf |
| 额外配置 | /etc/httpd/conf.d/*.conf |
| 网站根目录 | /var/www/html |
| 日志目录 | /var/log/httpd/ |
| 模块目录 | /usr/lib64/httpd/modules |
| 运行用户 | apache |
✅ 推荐:在 /etc/httpd/conf.d/ 中新建站点配置,不要直接改主配置
Listen 80
如需 HTTPS:
Listen 443
vim /etc/httpd/conf.d/example.conf
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html/example
<Directory "/var/www/html/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/html/example
CentOS 默认开启 SELinux,Apache 访问目录会被限制。
getenforce
semanage fcontext -a -t httpd_sys_content_t "/data/www(/.*)?"
restorecon -Rv /data/www
setsebool -P httpd_can_network_connect 1
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
yum install -y php php-cli php-common php-mysql
systemctl restart httpd
测试:
echo "<?php phpinfo(); ?>" > /var/www/html/info.php
Options -Indexes
ServerTokens Prod
ServerSignature Off
LoadModule deflate_module modules/mod_deflate.so
| 问题 | 排查方式 |
|---|---|
| 403 Forbidden | SELinux / 文件权限 |
| 无法访问 | firewalld / 监听端口 |
| 配置不生效 | httpd -t 检查语法 |
httpd -t
journalctl -xe -u httpd
Apache 适配 CentOS 的关键是:httpd + SELinux + firewalld + 正确的目录权限。
如果你愿意,我可以:
你现在是 学习 / 测试 / 生产环境?