如何让Apache根据请求域名返回对应不同索引文件?
Apache多域名对应不同首页的配置方法
前提准备
- 确保
www.domain1.com和www.domain2.com的DNS解析已指向你的服务器IP - 确认Apache已安装并正常运行
步骤1:启用虚拟主机模块(若未启用)
Debian/Ubuntu系统执行:
sudo a2enmod vhost_alias
RHEL/CentOS系统编辑/etc/httpd/conf/httpd.conf,确保以下行未被注释:
LoadModule vhost_alias_module modules/mod_vhost_alias.so Include conf/extra/httpd-vhosts.conf
步骤2:配置虚拟主机
方式一:分文件配置(推荐)
在Apache站点配置目录(Debian/Ubuntu为/etc/apache2/sites-available,RHEL/CentOS为/etc/httpd/conf.d)创建两个配置文件:
- domain1.conf
<VirtualHost *:80> ServerName www.domain1.com DocumentRoot /var/www/site DirectoryIndex index1.html <Directory /var/www/site> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>
- domain2.conf
<VirtualHost *:80> ServerName www.domain2.com DocumentRoot /var/www/site DirectoryIndex index2.html <Directory /var/www/site> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>
方式二:单文件配置
也可在同一个虚拟主机配置文件中写入两个<VirtualHost>块,内容与上述一致。
步骤3:启用站点并重启Apache
- Debian/Ubuntu系统:
sudo a2ensite domain1.conf domain2.conf sudo systemctl restart apache2
- RHEL/CentOS系统:
sudo systemctl restart httpd
验证效果
访问www.domain1.com会自动加载index1.html,访问www.domain2.com则加载index2.html;两个域名共享目录下的.css和.js文件,无需额外配置——因为DocumentRoot指向同一目录,资源路径会自动匹配。
内容的提问来源于stack exchange,提问作者cndfr
相关产品推荐
相关产品推荐

