首页 > 解决方案 > 使用 .htaccess 导航到 URL 中最后一个目录的父目录

问题描述

我正在尝试编写 .htaccess 代码,它将忽略 URL 的最终子目录,路由到该最终子目录之前的目录,但保持 URL 不变。

这是在我使用 JavaScript 进行路由的 SPA 的上下文中。

如果我导航到可以任意深度嵌套的目录 xxx:

https://my-site/[subdirectories]/xxx

...然后单击 xxx 目录中的相关链接时,例如:

./aaa
./bbb
./ccc

...这将对应于(并产生以下 URL):

https://my-site/[subdirectories]/xxx/aaa
https://my-site/[subdirectories]/xxx/bbb
https://my-site/[subdirectories]/xxx/ccc

...然后 JavaScript 将检测 URL 中的更改并显示“虚拟”子目录的内容aaa, bbb, ccc. 很好,花花公子。

但是,如果我直接访问这些 URL 中的任何一个,即直接输入 URL,而不是在站点内使用导航,那么我的站点会引发 404 错误,因为aaabbbccc不是实际的子目录。它们是“虚拟”子目录,与服务器上的实际文件夹不对应,因此会引发错误。

我想编写一个 .htaccess 例程来检测初始导航(直接打开):

https://my-site/[subdirectories]/xxx/aaa
https://my-site/[subdirectories]/xxx/bbb
https://my-site/[subdirectories]/xxx/ccc

等等

...只需打开此位置:

https://my-site/[subdirectories]/xxx

aaa...但保留 URL 末尾( , bbb, )的“虚拟”子目录,ccc如 URL 栏中显示的那样。我的 JavaScript 将从那里接管,为aaa, bbb, . 引入所需的内容ccc。(这在第一次https://my-site/[subdirectories]/xxx直接导航到然后只需单击指向aaa, bbb,的链接后就可以正常工作ccc;它会直接转到这些“子目录”中的任何一个,这就是问题所在。)

这可以用.htaccess 来完成吗?我正在挣扎。

标签: javascript.htaccessurlurl-rewritinghtml5-history

解决方案


诀窍是制定一个重写规则,为目标内容指定一个文件。

如果子目录名称是已知的,并且在本示例中它们是aaabbbccc,则以下规则将打开子目录中的 index.html 文件,同时保持 URL 不变:

RewriteEngine on

# If it's not an actual directory...
RewriteCond %{REQUEST_FILENAME} !-d

# If it's not an actual file...
RewriteCond %{REQUEST_FILENAME} !-f

# Provided aaa, bbb, and ccc are the known subdirectories,
# and (.+) represents ANY text that follows (i.e., any deeper
# subdirectory structure), then $1/index.html will route to
# the index.html file in whichever folder of the aaa|bbb|ccc list
# that is provided: 
RewriteRule ^(aaa|bbb|ccc)/(.+)$ $1/index.html [L]

推荐阅读