基于域名的虚拟主机是apache最常用的方式,它通过请求头中的host字段区分同一ip和端口下的多个站点;需确保dns或hosts解析生效、创建独立目录并设好权限、配置含servername和documentroot的virtualhost块、语法检查后重启服务。
基于域名的虚拟主机是 apache 最常用的方式,它让多个网站共用一个 ip 和同一个端口(通常是 80 或 443),靠请求头中的 host 字段区分目标站点。配置本身不复杂,但有几个关键点必须到位。
确保 DNS 或 hosts 解析生效
服务器需要能识别你输入的域名指向哪个 IP。开发或测试环境通常改本地 /etc/hosts:
- 192.168.10.10 www.site1.com
- 192.168.10.10 blog.site2.org
- 192.168.10.10 api.site3.net
生产环境则需在 DNS 服务商处添加 A 记录,把域名解析到服务器公网 IP。
创建独立网站目录和首页文件
每个域名对应一个文档根目录,避免混用:
- mkdir -p /var/www/site1
- mkdir -p /var/www/blog
- echo "Site1 Home" > /var/www/site1/index.html
- echo "Blog Site" > /var/www/blog/index.html
注意目录权限:Apache 进程(如 apache 或 www-data)需有读取权限,必要时执行 chown -R apache:apache /var/www/site1。
在 httpd.conf 或 conf.d 中添加虚拟主机块
推荐把配置单独放在 /etc/httpd/conf.d/vhost-domain.conf(CentOS/RHEL)或 /etc/apache2/sites-available/(Debian/Ubuntu),然后启用。
每个
<virtualhost>
ServerName www.site1.com
DocumentRoot "/var/www/site1"
<directory>
Require all granted
</directory></virtualhost><virtualhost>
ServerName blog.site2.org
ServerAlias www.site2.org
DocumentRoot "/var/www/blog"
<directory>
Require all granted
</directory></virtualhost>
使用 * 表示监听所有可用 IP 的 80 端口,无需指定具体 IP 地址。
检查并重启服务
配置完成后务必验证语法,再重启:
- httpd -t(CentOS/RHEL)或 apache2ctl configtest(Debian/Ubuntu)—— 输出 Syntax OK 才安全
- systemctl restart httpd 或 systemctl restart apache2
如果页面打不开,先确认防火墙放行 80 端口:firewall-cmd --permanent --add-port=80/tcp + firewall-cmd --reload(CentOS 7+)。











