【问题标题】:Using .htaccess to navigate to parent directory of last directory in URL使用 .htaccess 导航到 URL 中最后一个目录的父目录
【发布时间】:2019-11-13 10:12:12
【问题描述】:

我正在尝试编写 .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 中的更改并显示“虚拟”子目录 aaabbbccc 的内容。很好,花花公子。

但是,如果我直接访问这些 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

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

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

【问题讨论】:

    标签: javascript .htaccess url url-rewriting html5-history


    【解决方案1】:

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

    如果子目录名称已知,在本例中它们是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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-29
      • 2020-08-23
      • 2019-10-03
      • 2019-04-08
      • 2017-06-07
      • 2020-04-02
      • 2013-05-20
      • 1970-01-01
      相关资源
      最近更新 更多