[英].htaccess & mod_rewrite to rewrite to closest files
給出以下目錄結構:
/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]
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匹配的目錄,以用作重寫器的重寫庫。
您可以使用以下規則:
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]
這應該工作:
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.