javascript - 使用 .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 错误,因为aaa
、bbb
和ccc
不是实际的子目录。它们是“虚拟”子目录,与服务器上的实际文件夹不对应,因此会引发错误。
我想编写一个 .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 来完成吗?我正在挣扎。
解决方案
诀窍是制定一个重写规则,为目标内容指定一个文件。
如果子目录名称是已知的,并且在本示例中它们是aaa
、bbb
和ccc
,则以下规则将打开子目录中的 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]
推荐阅读
- scipy-optimize-minimize - Scipy 优化 PSSE 电力系统
- rdf - SHACL 验证列表并检索受约束的属性路径
- deep-learning - AttributeError: 'NoneType' 对象没有属性 'log' 这是什么意思?我该如何解决?
- react-native - 从持续时间中获取年月日小时分钟
- html - HTML5 音频播放列表在页面加载时开始不同
- python - 在 Pandas 和 Python 中打印数据框
- reactjs - React redux 共享整页依赖注入
- json - 将元素添加到嵌入在 MongoDB 的子文档中的数组中
- javascript - 你可以动态创建css类吗?
- javascript - 使用 JS、HTML 和 CSS 将多个下拉菜单彼此相邻添加