在 CentOS 上配置 Apache(httpd) 时,有几个常见且容易踩坑的点,下面按「系统层面 → Apache 配置 → 权限与安全 → 常见排错」给你梳理一下。
CentOS 7/8/Stream 推荐使用 yum / dnf:
# CentOS 7
yum install -y httpd
# CentOS 8 / Stream
dnf install -y httpd
检查版本:
httpd -v
systemctl start httpd
systemctl enable httpd
systemctl status httpd
⚠️ 修改配置后一定要重启或重载:
systemctl reload httpd
否则 本机可访问,外部访问不了
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
或临时关闭(不推荐):
systemctl stop firewalld
SELinux 会直接阻止 Apache 访问文件
getenforce
✅ 推荐(生产环境)
给目录设置正确的 SELinux 上下文:
chcon -R -t httpd_sys_content_t /var/www/html
✅ 允许 Apache 访问网络(如反向代理):
setsebool -P httpd_can_network_connect 1
❌ 不推荐:
setenforce 0
/etc/httpd/conf/httpd.conf
虚拟主机建议放:
/etc/httpd/conf.d/*.conf
Listen 80
Listen 443
检查是否被占用:
ss -lntp | grep httpd
否则启动会有警告:
ServerName www.example.com:80
或:
ServerName localhost
<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>
⚠️ 注意:
DocumentRoot 目录必须存在<Directory> 权限必须配置默认:
User apache
Group apache
网站目录权限建议:
chown -R apache:apache /var/www/html
chmod -R 755 /var/www/html
AllowOverride All
否则 .htaccess 不生效。
yum install -y mod_ssl
<VirtualHost *:443>
ServerName www.example.com
DocumentRoot /var/www/html/example
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/example.crt
SSLCertificateKeyFile /etc/pki/tls/private/example.key
</VirtualHost>
httpd -t
tail -f /var/log/httpd/error_log
tail -f /var/log/httpd/access_log
| 问题 | 原因 |
|---|---|
| 403 Forbidden | SELinux / 目录权限 / Directory 配置 |
| 页面打不开 | 防火墙没放行 |
| .htaccess 无效 | AllowOverride 没开 |
| 重启报错 | httpd -t 有语法错误 |
| 静态文件无法访问 | 目录权限或 SELinux |
✅ 使用独立 conf.d/*.conf
✅ 关闭目录浏览:
Options -Indexes
✅ 隐藏版本信息:
ServerTokens Prod
ServerSignature Off
如果你愿意,可以告诉我:
我可以给你一份可直接用的配置文件模板。