【问题标题】:.htaccess & mod_rewrite to rewrite to closest files.htaccess & mod_rewrite 重写到最近的文件
【发布时间】:2014-05-12 14:20:19
【问题描述】:

给定一个目录结构:

/test/
/test/a
/test/a/b
/test/a/b/c

在上面的示例中,每个目录都有一个索引文件 index.php。我在/test/ 中有一个 .htaccess ... 我想避免在每个目录中都有一个 .htaccess。

我需要编写一个重写规则,它将显示最接近输入到系统中的 URL 的 index.php。

例如:

url /test/a/b/1234 should get rewritten to /test/a/b/index.php
url /test/a/b/c/1234 should get rewritten to /test/a/b/cindex.php
url /test/1234 should get rewritten to /test/index.php

我尝试了几种不同的 .htaccess,但所有内容都被重写为 /test/index.php

<IfModule mod_rewrite.c>
      RewriteEngine On

      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d

      RewriteRule . index.php [L]
</IfModule>

我也试过RewriteRule . ./index.php [L]

如果我将 RewriteBase 设置为子目录之一,它会重写到该基础中的 index.php。但随后一切都被写入该基地。

提前致谢。

更新:

网址长度未知。示例:

url /test/a/b/1234/abcd/this/that/another should get rewritten to /test/a/b/index.php

基本上,我需要知道 .htaccess 从中匹配的目录,以用作重写器的重写库。

【问题讨论】:

  • 捕获1234 之前的部分,并将其用于替换...

标签: regex apache .htaccess mod-rewrite


【解决方案1】:

你可以使用这条规则:

RewriteEngine On

## recursively search parent dir
# if index.php is not found then
# forward to the parent directory of current URI
RewriteCond %{DOCUMENT_ROOT}/$1$2/index.php !-f
RewriteRule ^(.*?)([^/]+)/[^/]+/?$ /$1$2/ [L]

# if current index.php is found in parent dir then load it
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1index.php -f
RewriteRule ^(.*?)[^/]+/?$ /$1index.php [L]

【讨论】:

  • 这会因/a/b/1234/qwer/12321 的测试而失败,应该重写为/a/b/index.php
  • 为什么要把/a/b/1234/qwer/12321改写成/a/b/index.php?它将重写为/a/b/1234/qwer/index.php,因为那是父目录。你没写Each directory has an index file, index.php
  • 我作为示例给出的结构中的每个目录。其他任何东西都应该重写到最接近的 index.php
  • 答案可以和问题一样好。您从Each directory has an index file, index.php 开始,答案基于此。
  • 我从“给出这个目录结构”开始,我将更新以进行澄清。
【解决方案2】:

这应该可行:

RewriteEngine On
RewriteRule ^test/([A-Za-z]+)/([A-Za-z]+)/([A-Za-z]+)/([0-9]+)(.*)$ /test/$1/$2/$3/index.php [L]
RewriteRule ^test/([A-Za-z]+)/([A-Za-z]+)/([0-9]+)(.*)$ /test/$1/$2/index.php [L]
RewriteRule ^test/([0-9]+)(.*)$ /test/index.php [L]

【讨论】:

  • 此解决方案也不考虑任意目录深度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 2012-06-26
  • 2021-04-27
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
相关资源
最近更新 更多