如何在文档根目录外的别名目录中使用 .htaccess 使用重写规则

How to use rewrite rules using .htaccess in an aliased directory outside document root

我正在尝试使用 .htaccess 重写对未明确包含 .php 文件扩展名的 PHP 文件的请求(例如 example.com/foo 应重写为 example.com/foo.php),但 没有 将该规则应用于文档根目录的任何文件夹(或子文件夹)。

我的 http.conf 文件包含以下内容:

DocumentRoot "/webfiles"
<Directory "/webfiles">
  Options Indexes FollowSymLinks Includes ExecCGI
  AllowOverride All
  Require all granted
</Directory>

Alias "/exams" "/training/exams"
<Directory "/training/exams">
  Options Indexes FollowSymLinks Includes ExecCGI
  AllowOverride All
  Require all granted
</Directory>

DirectoryIndex index.php

/training/exams 文件夹中有一个 .htaccess 文件,其中包含以下内容:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ .php [NC,L]

目标是:

  1. 使用 /training/exams/index.php 文件处理 example.com/exams 这样的请求,
  2. 使用 /training/exams/first.php 文件为 example.com/exams/first 之类的请求提供服务,
  3. 同时 example.com/myhome.html 等请求仍由 /webfiles/myhome.html 处理。

示例 1. 和 3. 工作正常,但对于 2. 我收到 404 错误。

有趣的问题。

RewriteRule ^([^\.]+)$ .php [NC,L]

这最终会尝试将 URL 重写为 /training/exams/first.php(在添加回目录前缀之后)。我认为 mod_rewrite (在 目录 上下文中)将其视为 URL 路径并且 example.com/training/exams/first.php 不存在,因此 404 .

您可以使用 RewriteBase 指令用正确的相对根 URL 路径覆盖目录前缀。例如:

RewriteBase /exams

或者,在 RewriteRule 替换 中对 URL 路径进行硬编码。例如:

RewriteRule ^([^.]+)$ /exams/.php [L]

(在字符 class 中使用时不需要 NC 标志或转义文字点。)

或者,使用 REQUEST_URI 服务器变量构造根目录相对 URL-路径:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]