在Apache服务器上配置虚拟主机

一、什么是虚拟主机?

一台服务器 + 一个 IP → 跑多个网站

比如:

  • www.a.com → 指向 /var/www/a
  • www.b.com → 指向 /var/www/b

二、准备工作

  1. Apache 已安装并正常运行
  2. 准备两个网站目录
  3. 开启虚拟主机配置(大部分系统默认已开)

三、第一步:创建网站目录(放网页)

Linux(CentOS / Ubuntu)

bash
运行
# 站点1
mkdir -p /var/www/a
echo "站点A" > /var/www/a/index.html

# 站点2
mkdir -p /var/www/b
echo "站点B" > /var/www/b/index.html

Windows(XAMPP)

plaintext
D:\xampp\htdocs\a\index.html
D:\xampp\htdocs\b\index.html

四、第二步:修改配置文件(核心)

1. 找到配置文件

Linux CentOS

bash
运行
/etc/httpd/conf.d/vhost.conf
(没有就新建)

Linux Ubuntu

bash
运行
/etc/apache2/sites-available/000-default.conf

Windows XAMPP

打开:
plaintext
xampp/apache/conf/extra/httpd-vhosts.conf

2. 直接复制以下配置(改域名和路径即可)

apache
# 站点1:www.a.com
<VirtualHost *:80>
    ServerName www.a.com
    DocumentRoot /var/www/a  # 网站目录
    ErrorLog logs/a-error.log
    CustomLog logs/a-access.log common
</VirtualHost>

# 站点2:www.b.com
<VirtualHost *:80>
    ServerName www.b.com
    DocumentRoot /var/www/b  # 网站目录
    ErrorLog logs/b-error.log
    CustomLog logs/b-access.log common
</VirtualHost>

Windows XAMPP 写法

apache
<VirtualHost *:80>
    ServerName www.a.com
    DocumentRoot "D:/xampp/htdocs/a"
</VirtualHost>

<VirtualHost *:80>
    ServerName www.b.com
    DocumentRoot "D:/xampp/htdocs/b"
</VirtualHost>

五、第三步:确保主配置开启了虚拟主机

Windows XAMPP

打开 httpd.conf,确保这一行没有 #
apache
Include conf/extra/httpd-vhosts.conf

Linux

一般默认已开启,无需操作。

六、第四步:重启 Apache

Linux CentOS

bash
运行
systemctl restart httpd

Linux Ubuntu

bash
运行
systemctl restart apache2

Windows

XAMPP → Stop Apache → Start Apache

七、第五步:本地测试(关键)

如果你没有真实域名,修改本地 hosts 文件就能测试:

Windows 路径

plaintext
C:\Windows\System32\drivers\etc\hosts

Linux / Mac 路径

plaintext
/etc/hosts
添加:
plaintext
127.0.0.1  www.a.com
127.0.0.1  www.b.com
然后浏览器访问:
plaintext
http://www.a.com
http://www.b.com
能分别看到不同页面 = 成功 ✅

八、最常见错误(90% 的人踩坑)

1. 访问所有域名都打开同一个网站

原因:没有配置 ServerName

解决:每个 <VirtualHost> 必须写 ServerName 域名

2. 403 无权限

确保目录权限配置:
apache
<Directory "/var/www/a">
    AllowOverride All
    Require all granted
</Directory>

3. 配置不生效

  • 配置文件路径写错
  • 没有重启 Apache
  • 域名没解析 /hosts 没改

九、如果你要配置 HTTPS 虚拟主机

直接在 443 端口配置即可:
apache
<VirtualHost *:443>
    ServerName www.a.com
    DocumentRoot /var/www/a
    SSLEngine on
    SSLCertificateFile /etc/httpd/ssl/a.crt
    SSLCertificateKeyFile /etc/httpd/ssl/a.key
</VirtualHost>

总结

  1. 两个网站目录
  2. 两个 VirtualHost 配置
  3. 填好 ServerNameDocumentRoot
  4. 重启 Apache
  5. 本地改 hosts 测试
上一篇 MyBatis轻松接入金仓数据库:从零搭建到生产实践
下一篇 U盘安装CentOS7提示“Warning :dracut-initqueue timeout - starting timeout scripts” 解决办法