【问题标题】:htaccess reverse directoryhtaccess 反向目录
【发布时间】:2012-05-16 07:19:04
【问题描述】:

是否可以让htaccess查找与该url相关的特定文件,如果找不到则返回上一步?

例子:

/示例/这里/哪里/从

Htaccess 会检查“/example/here/where/from”是否确实是某种文件(/example/here/where/from.php),如果失败,它会返回一步并检查“”/ example/here/where' 是一个文件(/example/here/where.php)等等。

如果它必须回到树中,假设它们为参数,如下所示:

/example/here.php

$_GET['params'] = '哪里/来自';

提前致谢

编辑:

拼写

【问题讨论】:

  • 这是一个固定的深度(例如,在你的例子中它是最大 4 项深度),还是你希望能够处理无限深度?

标签: php apache .htaccess redirect


【解决方案1】:

这很棘手,但这是一个递归遍历给定 REQUEST_URI 的父目录的代码,它支持无限深度。

通过httpd.conf启用mod_rewrite和.htaccess,然后把这段代码放到你.htaccessDOCUMENT_ROOT目录下:

# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
# If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
# don't do anything
RewriteRule ^ - [L]

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

# if current ${REQUEST_URI}.php is a valid file then 
# load it be removing optional trailing slash
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

说明:

假设原始 URI 是:/index/foo/bar/baz。另外假设%{DOCUMENT_ROOT}/index.php 存在,但DOCUMENT_ROOT 下不存在其他php 文件。

RewriteRule #1 有一个正则表达式,它将当前的 REQUEST_URI 分成两部分:

  1. 除了$1 的最低子目录之外的所有子目录,这里将是index/foo/bar
  2. $2 的最低子目录,此处为baz

RewriteCond 检查%{DOCUMENT_ROOT}/$1/$2.php(转换为%{DOCUMENT_ROOT}/index/foo/bar/baz.php)是否不是有效文件。

如果条件成功,则在内部重定向到$1/,此处为index/foo/bar/

RewriteRule #1 的逻辑再次重复以使 REQUEST_URI 为(在每次递归之后):

  1. index/foo/bar/
  2. index/foo/
  3. index/

此时,规则 #1 的 RewriteCond 失败,因为那里存在 ${DOCUMENT_ROOT}/index.php

如果 %{DOCUMENT_ROOT}/$1.php 是一个有效文件,我的 RewriteRule #2 会转发到 $1.php。请注意,RewriteRule #2 具有匹配除最后一个斜杠之外的所有内容的正则表达式,并将其放入$1。这意味着检查%{DOCUMENT_ROOT}/index.php 是否为有效文件(确实如此)。

此时 mod_rewrite 处理已完成,因为此后两个 RewriteCond 都失败了,因此无法触发进一步的规则,因此 %{DOCUMENT_ROOT}/index.php 将由您的 Apache Web 服务器适当地提供服务。

【讨论】:

  • 我对递归逻辑感到非常疲惫,我跳过了解释部分,现在添加它:)
  • @john:添加了一些解释。
  • 谢谢,这个回答这个问题,你能看看这个吗? [问题]:stackoverflow.com/questions/10496267/…
  • 很好的答案,我一直在寻找这样的东西,很长一段时间。虽然我必须做一些调整才能为我工作: 1. 删除“RewriteBase /” 2. 切换:RewriteCond %{DOCUMENT_ROOT}/$1.php -f for RewriteCond %{REQUEST_FILENAME}.php -f 第二个修复是使用没有 .php 的页面,自动添加它。例如:www.somesime.com/home.php/a/b/c www.somesime.com/home/a/b/c 两者都可以。
猜你喜欢
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
相关资源
最近更新 更多