一、虚拟主机是什么?
一台服务器、一个 IP,跑多个独立网站:
二、3 步完成配置(最简单版)
第 1 步:准备网站目录
Windows(XAMPP)
plaintext
D:\xampp\htdocs\site1
D:\xampp\htdocs\site2
每个目录里放一个
index.html 测试。Linux
bash
运行
mkdir -p /var/www/site1
mkdir -p /var/www/site2
echo "site1" > /var/www/site1/index.html
echo "site2" > /var/www/site2/index.html
第 2 步:配置虚拟主机(核心)
配置文件位置
- Windows XAMPP:
xampp/apache/conf/extra/httpd-vhosts.conf - Linux CentOS:
/etc/httpd/conf.d/vhost.conf - Linux Ubuntu:
/etc/apache2/sites-available/000-default.conf
直接复制这段配置(改路径即可)
apache
# 网站1
<VirtualHost *:80>
ServerName www.site1.com
DocumentRoot "D:/xampp/htdocs/site1"
<Directory "D:/xampp/htdocs/site1">
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
# 网站2
<VirtualHost *:80>
ServerName www.site2.com
DocumentRoot "D:/xampp/htdocs/site2"
<Directory "D:/xampp/htdocs/site2">
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Linux 版本只需改路径:
apache
DocumentRoot /var/www/site1
第 3 步:重启 Apache
- Windows:XAMPP → Stop → Start
- Linux:
bash运行
systemctl restart httpd # CentOS systemctl restart apache2 # Ubuntu
三、本地测试(没有域名也能测)
修改本机
hosts 文件:Windows
plaintext
C:\Windows\System32\drivers\etc\hosts
添加:
plaintext
127.0.0.1 www.site1.com
127.0.0.1 www.site2.com
Linux/Mac
plaintext
/etc/hosts
然后浏览器访问:
plaintext
http://www.site1.com
http://www.site2.com
能看到不同页面 = 成功 ✅
四、最常见 3 个问题
- 所有域名打开同一个站
没写
ServerName - 403 无权限
缺少
<Directory>里的Require all granted - 配置不生效
没重启 Apache
总结
- 建两个网站目录
- 写两个 VirtualHost 配置
- 填好
ServerName+DocumentRoot - 重启 Apache