apache基于名称的虚拟主机通过host请求头将同一ip和端口的请求分发到不同目录,需启用httpd-vhosts.conf、配置、设置servername与本地hosts映射,并重启服务验证。
在 apache 中配置基于名称的虚拟主机(name-based virtual host),核心是让同一台服务器、同一个 ip 地址和端口,根据浏览器请求里的 host 请求头,自动分发到不同网站目录。它不依赖额外 ip,适合绝大多数本地开发和生产场景。
确认 Apache 已启用虚拟主机支持
打开主配置文件(如 httpd.conf 或 apache2.conf),确保以下两行未被注释:
- Include conf/extra/httpd-vhosts.conf(或类似路径,指向虚拟主机配置文件)
- Listen 80(确保监听了目标端口)
如果使用的是较新版本 Apache(2.4+),NameVirtualHost 指令已废弃,无需手动添加 —— 只要
准备网站目录与测试页面
为每个域名建独立根目录,例如:
- /var/www/site-a → 放 index.html,内容写 “Site A”
- /var/www/site-b → 放 index.html,内容写 “Site B”
确保 Apache 进程有读取权限(Linux 下可执行 sudo chown -R $USER:www-data /var/www/site-*)。
编辑虚拟主机配置文件
打开 conf/extra/httpd-vhosts.conf(或你 Include 的那个文件),写入类似以下内容:
<virtualhost>
ServerName site-a.local
DocumentRoot "/var/www/site-a"
<directory>
Require all granted
</directory></virtualhost><virtualhost>
ServerName site-b.local
DocumentRoot "/var/www/site-b"
<directory>
Require all granted
</directory></virtualhost>
注意:ServerName 必须与你后续访问时输入的域名完全一致;多个域名可用 ServerAlias 补充,比如加一行 ServerAlias www.site-a.local。
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
本地 DNS 映射(仅开发用)
在系统 hosts 文件中添加映射(Windows 在 C:\Windows\System32\drivers\etc\hosts,macOS/Linux 在 /etc/hosts):
127.0.0.1 site-a.local 127.0.0.1 site-b.local
保存后无需重启网络,但浏览器可能需清缓存或换无痕窗口测试。
验证并重启 Apache
运行命令检查语法是否正确:
- Linux/macOS:sudo apachectl configtest 或 sudo apache2ctl configtest
- Windows(XAMPP):httpd -t(在 XAMPP 控制面板里也可点“Config → Apache (httpd.conf)”后选“Syntax Check”)
无报错后重启服务:
- Linux(systemd):sudo systemctl restart apache2
- macOS(Homebrew):brew services restart httpd
- Windows(XAMPP):控制面板里 Stop 再 Start Apache
最后在浏览器分别访问 http://site-a.local 和 http://site-b.local,看到对应页面即成功。










