You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Apache httpd中将不存在的子目录请求映射至根目录文件?

修复Apache虚拟主机配置实现/dir3路径映射

问题分析

当前配置的核心问题:

  • 错误使用Alias指令引发路径映射冲突
  • 重复开启RewriteEngine且规则逻辑错误,误用301跳转而非内部重写
  • 规则未正确匹配/dir3及子路径的请求

正确配置方案

替换原虚拟主机配置中的Alias及Rewrite相关内容,使用以下完整配置:

<IfModule mod_ssl.c>
<VirtualHost *:443>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/html
  ServerAdmin info@example.com

  <Directory /var/www/html>
    AllowOverride None
    Require all granted
  </Directory>

  RewriteEngine On
  # 处理/dir3请求,返回根目录index.php
  RewriteRule ^/dir3$ /index.php [L]
  # 处理/dir3/xxx请求,返回根目录对应xxx文件
  RewriteRule ^/dir3/(.*)$ /$1 [L]

  Include /etc/letsencrypt/options-ssl-apache.conf
  SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>

关键说明

  1. 移除Alias /dir3 "/var/www/html":避免该指令与Rewrite规则的路径解析逻辑冲突
  2. 两条Rewrite规则分工:
    • 第一条精准匹配/dir3(不带斜杠)的请求,内部重写到根目录index.php
    • 第二条匹配/dir3/后带任意路径的请求,将/dir3/xxx映射为/xxx,直接返回根目录对应文件
  3. [L]标记:匹配当前规则后停止执行后续Rewrite规则,避免冗余处理
  4. Require all granted:确保Apache 2.4+版本下允许访问根目录内容(原配置已有可直接保留)

生效操作

修改配置后重启Apache服务:

systemctl restart httpd

内容的提问来源于stack exchange,提问作者Alfred

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:42:46