简体   繁体   English

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

[英].htaccess & mod_rewrite to rewrite to closest files

given a directory structure of: 给出以下目录结构:

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

Each directory, in the above example, has an index file, index.php, in it. 在上面的示例中,每个目录中都有一个索引文件index.php。 I have a single .htaccess in /test/ ... I would like to avoid having a .htaccess in each directory. 我在/test/只有一个.htaccess ...我想避免在每个目录中都有一个.htaccess。

I need to write a rewrite rule that will display the closest index.php to a URL that is entered into a system. 我需要编写一个重写规则,该规则将显示与输入到系统中的URL最接近的index.php。

For example: 例如:

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

I've tried several different .htaccess, but everything gets 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>

I've also tried RewriteRule . ./index.php [L] 我也尝试过RewriteRule . ./index.php [L] RewriteRule . ./index.php [L]

If i set a RewriteBase to be one of the sub directories it does rewrite to the index.php in that base. 如果我将RewriteBase设置为子目录之一,则确实会将其重写为该目录中的index.php。 but then everything gets written to that base. 但随后一切都写入该基础。

Thanks in advance. 提前致谢。

Update: 更新:

The url length is unknown. 网址长度未知。 Example: 例:

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

Essentially, I need to know the directory from which .htaccess was matched in to use as the rewritebase for the rewriterule. 本质上,我需要知道与.htaccess匹配的目录,以用作重写器的重写库。

You can use this rule: 您可以使用以下规则:

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]

This should work: 这应该工作:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM