在 CentOS 上配置 Apache(httpd)可以分为 安装、启动、目录配置、虚拟主机、防火墙/SELinux、常见优化 几个部分。下面以 CentOS 7 / 8 为例说明(CentOS 6 已过时,不再推荐)。
# CentOS 7
yum install -y httpd
# CentOS 8(或 CentOS Stream)
dnf install -y httpd
查看版本:
httpd -v
systemctl start httpd
systemctl enable httpd
systemctl status httpd
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
firewall-cmd --list-all
getenforce
Enforcing:需要配置Permissive:可暂时忽略Disabled:不推荐setsebool -P httpd_read_user_content 1
setsebool -P httpd_enable_homedirs 1
如果你使用非默认目录(如 /data/www),需要:
semanage fcontext -a -t httpd_sys_content_t "/data/www(/.*)?"
restorecon -Rv /data/www
| 作用 | 路径 |
|---|---|
| 主配置文件 | /etc/httpd/conf/httpd.conf |
| 虚拟主机配置 | /etc/httpd/conf.d/*.conf |
| 默认网站目录 | /var/www/html |
| 日志 | /var/log/httpd/ |
echo "Hello CentOS Apache" > /var/www/html/index.html
浏览器访问:
http://服务器IP
mkdir -p /var/www/example.com
echo "example.com" > /var/www/example.com/index.html
vi /etc/httpd/conf.d/example.conf
内容示例:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example.com
<Directory /var/www/example.com>
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/example_error.log
CustomLog /var/log/httpd/example_access.log combined
</VirtualHost>
systemctl restart httpd
确保:
AllowOverride All
并加载模块(默认已加载):
httpd -M | grep rewrite
Options -Indexes
LoadModule deflate_module modules/mod_deflate.so
Require all granted 未配置systemctl status httpd
journalctl -xe
cat /var/log/httpd/error_log
安装 httpd
启动并设置开机自启
配置防火墙
处理 SELinux
配置虚拟主机
重启 httpd
如果你需要:
可以直接告诉我你的 CentOS 版本和使用场景,我可以给你一套完整配置方案。