.htaccess 需要帮助来处理对非根文件夹中 index.php 的请求

.htaccess need help to serve requests to index.php in non root folder

我有一个特定的网站结构:

root:

styles.css
pages/index.html
folder_with_assets_1
folder_with_assets_2
folder_with_images

我已将 index.html 重命名为 index.php 以摆脱 URL

中的 .html 扩展名

但问题是 index.php 不在根文件夹中,它在 pages 文件夹中。 哪项 .htaccess 规则可以解决将请求重定向到 pages 文件夹的问题?

更新 具有文件夹结构的屏幕截图:

从表面上看,这只是一个标准的前端控制器模式。前端控制器是位于子目录内还是直接位于文档根目录中,这在很大程度上是无关紧要的——过程是一样的。

假设您在文档根目录中使用 .htaccess 文件并且 页面 URLs...

例如,使用mod_dir FallbackResource:

FallbackResource /pages/index.php

或者,使用 mod_rewrite:

DirectoryIndex /pages/index.php

RewriteEngine On

RewriteRule (^|/)index\.php - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . pages/index.php [L]

更新#1:

It's "onepage" website format with plenty of JS and CSS. There are only local URLs pointing to sections (href tag) and AJAX call to specific PHP files

在那种情况下,看起来您需要更改 DirectoryIndex - 您根本不需要前端控制器模式(如上所述)。

例如:

DirectoryIndex /pages/index.php

现在,对“主页”的请求,即文档根目录 https://example.com/ 将提供 /pages/index.php


更新#2:

从您的屏幕截图来看,目录列表 (mod_autoindex) 似乎已启用。这些应该在 .htaccess 文件的顶部被禁用:

Options -Indexes

更新#3:

从您的屏幕截图来看,您在文件结构中所谓的“根目录”似乎实际上并不是您网站的“文档根目录”,因为您是通过 /test 子目录访问该位置的,即. localhost/test/。上面的指令假设这些文件位于“文档根目录”中,即。 localhost/ 并且没有 /test 子目录。 (我希望它是如何在您的“实时”环境中构建的?)

如果您的 .htaccess 文件位于 /test 子目录中,并且您正在请求 localhost/test/(根据您的屏幕截图),那么您需要相应地进行调整:

例如:

DirectoryIndex /test/pages/index.php

但是,这在实时站点上不起作用(假设您在实时站点上没有 /test 子目录)。相反,您可以简单地省略斜杠前缀,使其成为 relative.

例如:

DirectoryIndex pages/index.php

这对你的情况应该没问题,因为你有一个 SPA(只是一个主页 URL)。