【问题标题】:Recursively look in subdirectories for matching filename.递归地在子目录中查找匹配的文件名。
【发布时间】:2014-08-13 09:55:08
【问题描述】:

如果找不到文件,我想递归检查子目录,直到找到具有请求名称的文件并交付。

示例:

请求是:

http://domain.com/file.txt

递归查找子目录,直到找到file.txt,然后传递:

http://domain.com/foo/bar/file.txt

到目前为止,我唯一管理的是找不到文件时的触发器:

RewriteCond %{REQUEST_FILENAME} !-f

【问题讨论】:

  • 规则可以检查已知的子目录,但不能从每个路径生成目录列表。
  • @anubhava:感谢您提供的信息。不幸的是,子目录列表是未知的,也可以动态更改。
  • 那么重写规则将没有任何帮助。最好在服务器端做。

标签: apache .htaccess http mod-rewrite


【解决方案1】:

将其放入加载程序脚本中。首先,在您的应用程序中进行此重写(vhost 配置或 .htaccess 文件)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /loader.php?q=$1 [L,QSA]

然后在您网站的根目录中有一个loader.php 脚本,它将递归搜索文件并重定向到正确的 URL 或加载文件,获取 mime 提示,设置正确的标题并以该文件的内容。像这样的:

<?php
// Do some processing here to extract the proper file name
// from $_REQUEST['q'] into a variable called $filename

// Assume we have the $filename
$it = new RecursiveDirectoryIterator(__DIR__); // Start search where loader.php is located
foreach (new RecursiveIteratorIterator($it) as $file) {
    if (pathinfo($file, PATHINFO_BASENAME) == $filename) {
        $returnFile = $file;
        break;
    }
}

// Check if the file was found
// Do a proper redirect to the 404 page here if you need more
if (empty($returnFile)) {
    header ("HTTP/1.0 404 Not Found");
    die();
}

// You need to do some fancy magic here to set the proper content type
// We will return plain text for now
header("Content-Type:text/plain");

// Handle large files
set_time_limit(0);
$file = @fopen($file_path,"rb");
while(!feof($file))
{
    print(@fread($file, 1024*8));
    ob_flush();
    flush();
}

/* EndOfScript */

就是这样,我猜...我根本没有测试过这个,所以它可能有很多问题!再说一遍,您可以大致了解如何处理此问题!

【讨论】:

    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多