首页 文章

.htaccess&mod_rewrite重写为最近的文件

提问于
浏览
1

给定目录结构:

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

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

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

例如:

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的目录,以用作重写的重写库 .

2 回答

  • 0

    您可以使用此规则:

    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]
    
  • 0

    这应该工作:

    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]
    

相关问题