温馨提示×

Apache如何在CentOS创建虚拟主机

小樊
43
2026-07-20 09:14:06
栏目: 云计算

下面以 CentOS 7 / CentOS 8(含 Rocky / Alma 同理) 为例,介绍 Apache 创建虚拟主机(Virtual Host) 的完整流程。示例基于 Apache 2.4


一、前提条件

  1. 已安装 Apache
# CentOS 7
yum install -y httpd

# CentOS 8 / Rocky / Alma
dnf install -y httpd
  1. 启动并设置开机自启
systemctl start httpd
systemctl enable httpd
  1. 防火墙放行 HTTP/HTTPS
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

二、创建网站目录

以域名 example.com 为例:

mkdir -p /var/www/example.com/public_html
mkdir -p /var/www/example.com/logs

设置权限:

chown -R apache:apache /var/www/example.com
chmod -R 755 /var/www

三、创建虚拟主机配置文件

1️⃣ 新建配置文件

vim /etc/httpd/conf.d/example.com.conf

2️⃣ 写入虚拟主机配置

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html

    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/www/example.com/logs/error.log
    CustomLog /var/www/example.com/logs/access.log combined
</VirtualHost>

✅ 说明:

  • ServerName:主域名
  • ServerAlias:别名(可选)
  • DocumentRoot:网站根目录
  • AllowOverride All:支持 .htaccess
  • Require all granted:允许访问(Apache 2.4)

四、创建测试页面

echo "<h1>Welcome to example.com</h1>" > /var/www/example.com/public_html/index.html

五、检查并重启 Apache

检查配置

httpd -t

重启服务

systemctl restart httpd

六、本地测试(无真实域名)

修改 hosts 文件(Windows / Linux / macOS)

服务器IP  example.com

浏览器访问:

http://example.com

七、常见问题

❌ 403 Forbidden

  • 目录权限不足
  • SELinux 未放行

✅ 解决 SELinux:

setsebool -P httpd_read_user_content 1

或临时关闭(不推荐):

setenforce 0

❌ 虚拟主机不生效

  • 配置文件未放在 /etc/httpd/conf.d/
  • 端口不是 80
  • ServerName 写错

八、一个服务器多个虚拟主机

只需再创建一个 .conf 文件即可,例如:

/etc/httpd/conf.d/test.com.conf

九、总结流程

安装 Apache
↓
创建网站目录
↓
编写虚拟主机配置
↓
测试配置
↓
重启 Apache
↓
访问域名

如果你需要:

  • HTTPS(Let’s Encrypt + SSL)
  • Apache + PHP / Python
  • CentOS 6 或 Rocky / Alma 差异
  • 伪静态 / .htaccess

可以直接告诉我,我可以一步步帮你配置。

0