Apache多站点配置异常:仅显示单个站点的问题排查
问题解决步骤
一、修正本地域名映射(hosts文件)
你的虚拟主机配置使用了ServerName a4和ServerName mad,但当前用localhost/a4这类路径访问的方式,完全违背了虚拟主机的工作逻辑——虚拟主机是基于请求的Host头匹配站点,而非路径前缀。
编辑/etc/hosts文件,添加以下两行:
127.0.0.1 a4 127.0.0.1 mad
保存后,直接通过http://a4访问第一个站点,http://mad访问第二个站点,这才是虚拟主机的正确访问方式。
二、修复.htaccess的URL重写规则
两个站点的.htaccess最后一条重写规则存在致命问题:
RewriteRule . /index.php [L]
这里的/index.php是服务器根路径,而非站点根路径。当访问localhost/mad时,请求会匹配默认虚拟主机(a4,因为它是第一个加载的),这条规则会把请求重定向到服务器根目录下的index.php,也就是/var/www/html/a4/index.php,因此会跳转到a4站点。
修正a4的.htaccess
将最后一行改为相对路径(基于已设置的RewriteBase /a4/):
RewriteEngine On RewriteBase /a4/ RewriteRule ^(index\.php|mad(/.*)?)$ - [L] RewriteRule ^phpmyadmin(/.*)?$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 改为相对路径,移除开头的/ RewriteRule . index.php [L]
修正mad的.htaccess
同样修改最后一行:
RewriteEngine On RewriteBase /mad/ # Ignora le richieste per index.php RewriteRule ^index\.php$ - [L] RewriteRule ^phpmyadmin(/.*)?$ - [L] # Controlla se il file o la directory richiesta esistono RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 改为相对路径,移除开头的/ RewriteRule . index.php [L]
三、确认虚拟主机配置与启用状态
- 确保两个站点的配置文件已正确启用:
sudo a2ensite a4.conf sudo a2ensite mad.conf
- 禁用默认站点(若之前未完成):
sudo a2dissite 000-default.conf
- 重启Apache服务使配置生效:
sudo systemctl restart apache2
问题根源说明
- 访问localhost/a4出现404:禁用默认站点后,Apache会将第一个加载的虚拟主机(a4)设为默认站点,
localhost的请求会匹配a4的虚拟主机。由于a4的文档根是/var/www/html/a4,localhost/a4等价于请求/var/www/html/a4/a4/目录,该目录不存在,因此返回404。 - 访问localhost/mad跳转到a4:同理,
localhost/mad会匹配a4的虚拟主机,.htaccess中的重写规则将请求导向服务器根目录的index.php,也就是a4的首页。
内容的提问来源于stack exchange,提问作者SUPERPUGN0
相关产品推荐
相关产品推荐

