在 CentOS 上配置 Apache 虚拟主机(Virtual Host),通常用于在一台服务器上运行多个网站。下面以 CentOS 7/8 + Apache(httpd) 为例,给你一个完整、常用、可操作的配置流程。
# CentOS 7
yum install httpd -y
# CentOS 8 / Stream
dnf install httpd -y
systemctl start httpd
systemctl enable httpd
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
示例:
/var/www/
├── site1
│ └── index.html
├── site2
│ └── index.html
创建目录:
mkdir -p /var/www/site1
mkdir -p /var/www/site2
创建测试页面:
echo "site1" > /var/www/site1/index.html
echo "site2" > /var/www/site2/index.html
在:
/etc/httpd/conf.d/
创建配置文件:
vim /etc/httpd/conf.d/site1.conf
内容:
<VirtualHost *:80>
ServerName www.site1.com
DocumentRoot /var/www/site1
<Directory /var/www/site1>
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/site1_error.log
CustomLog /var/log/httpd/site1_access.log combined
</VirtualHost>
vim /etc/httpd/conf.d/site2.conf
<VirtualHost *:80>
ServerName www.site2.com
DocumentRoot /var/www/site2
<Directory /var/www/site2>
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/site2_error.log
CustomLog /var/log/httpd/site2_access.log combined
</VirtualHost>
httpd -t
systemctl restart httpd
192.168.1.100 www.site1.com
192.168.1.100 www.site2.com
浏览器访问:
http://www.site1.com
http://www.site2.com
原因:
解决方法:
chown -R apache:apache /var/www/site1
chown -R apache:apache /var/www/site2
SELinux(常见坑):
setsebool -P httpd_read_user_content 1
或暂时关闭测试:
setenforce 0
如启用 HTTPS:
<VirtualHost *:443>
ServerName www.site1.com
DocumentRoot /var/www/site1
SSLEngine on
SSLCertificateFile /path/to/cert.crt
SSLCertificateKeyFile /path/to/key.key
</VirtualHost>
1. 安装 httpd
2. 创建网站目录
3. 在 /etc/httpd/conf.d/ 写 *.conf
4. httpd -t → systemctl restart httpd
5. 测试访问
如果你需要:
可以直接告诉我,我可以给你一步一步实战配置。