Apache基于域名的虚拟主机核心是通过请求头Host字段区分域名并路由至对应目录,无需多IP或多端口;需创建独立网站目录、配置ServerName/DocumentRoot、权限(Require all granted)、检查语法后重启服务,并通过hosts文件或DNS验证。
apache 配置基于域名的虚拟主机,核心是让同一台服务器通过请求头中的 host 字段区分不同域名,并将流量路由到对应网站目录。它不需要多个 ip 或端口,适合绝大多数多站点场景。
准备网站目录和基础文件
为每个域名创建独立根目录,并放入可访问的首页文件:
- 创建目录结构,例如:
mkdir -p /var/www/www.example.com/public_html<br>mkdir -p /var/www/blog.example.com/public_html
- 在每个目录中添加测试页面,如
/var/www/www.example.com/public_html/index.html写入www.example.com
- 确保目录权限允许 Apache 读取(通常属主为
root,其他用户有读+执行权限)
启用并配置虚拟主机模块
确认 Apache 已加载必要模块(现代版本默认启用),并在主配置中启用虚拟主机支持:
- 编辑主配置文件
/etc/httpd/conf/httpd.conf(CentOS/RHEL)或/etc/apache2/apache2.conf(Debian/Ubuntu) - 取消注释这一行(若存在且被注释):
Include conf/extra/httpd-vhosts.conf或IncludeOptional sites-enabled/*.conf - 确保
NameVirtualHost *:80已启用(Apache 2.4+ 通常不再需要显式声明,*:80在中已隐含)
编写域名虚拟主机配置
在 httpd-vhosts.conf 或单独的站点配置文件中,为每个域名添加一个 块:
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
- 必须包含
ServerName(主域名)和DocumentRoot(网站根路径) - 推荐添加
ServerAlias支持 www 和无 www 访问,例如:ServerAlias example.com www.example.com - 必须配置
段,明确授权访问权限(Apache 2.4 要求Require all granted) - 示例片段:
<virtualhost>
ServerName www.example.com
ServerAlias example.com
DocumentRoot "/var/www/www.example.com/public_html"
<directory>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</directory>
ErrorLog "/var/log/httpd/www-example-error.log"
CustomLog "/var/log/httpd/www-example-access.log" combined
</virtualhost>完成部署与验证
配置完成后需检查语法、重启服务,并确保 DNS 或本地解析生效:
- 检查配置是否合法:
apachectl configtest或httpd -t(返回Syntax OK表示无误) - 重启 Apache:
systemctl restart httpd(RHEL/CentOS)或systemctl restart apache2(Debian/Ubuntu) - 本地测试:修改
/etc/hosts(Linux/macOS)或C:\Windows\System32\drivers\etc\hosts(Windows),添加:127.0.0.1 www.example.com blog.example.com - 浏览器访问
http://www.example.com,确认显示对应页面;用curl -H "Host: blog.example.com" http://127.0.0.1可绕过 DNS 验证路由逻辑










