简体   繁体   English

使用HTaccess重定向到子文件夹(如果其中包含所请求的文件)

[英]Using HTaccess to redirect to a subfolder if it contains the requested file

I'm trying to load some content from the database, and cache it in a folder on the server. 我正在尝试从数据库中加载一些内容,并将其缓存在服务器上的文件夹中。 Currently, I'm using this code to catch requests to http://localhost/files/hash.png and pass the hash and filetype to a PHP file which returns the data. 当前,我正在使用此代码来捕获对http://localhost/files/hash.png请求,并将哈希和文件类型传递给返回数据的PHP文件。

Files can have any extension, so I need to either catch the full filename (that's fine), or split it into name and extension (also fine). 文件可以具有任何扩展名,因此我需要捕获完整的文件名(可以),或将其拆分为名称和扩展名(也可以)。

Here's my HTaccess: 这是我的HTaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^files/([^\.]+)\.([^\.]+)$ getfile.php?hash=$1&ext=$2 [NC,L]

The problem is, I'm now needing to tell it to try to find hash.png in a subfolder of files called cache (ie files/cache/hash.png ). 问题是,我现在需要告诉它尝试在名为cachefiles的子files夹中找到hash.png (即files/cache/hash.png )。 This would need to be loaded instead of the PHP file, should the file exist in that folder. 如果该文件存在于该文件夹中,则需要加载该文件而不是PHP文件。

Can anyone help? 有人可以帮忙吗? I'm struggling to get it working. 我正在努力使其正常运行。 This is to do a kind of caching on files stored in a database. 这是对存储在数据库中的文件进行某种缓存。

RewriteEngine On
RewriteRule ^files/(.*) files/cache/$1 [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule *. - [L]
RewriteRule ^files/cache/(.*) files/$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^files/([^\.]+)\.([^\.]+)$ getfile.php?hash=$1&ext=$2 [NC,L]

Here it's rewriting the file name to alter the path to file/cache/ before testing if it exists. 在这里,它在测试文件名是否存在之前,重写文件名以更改file/cache/的路径。 If it exists, don't change the file name and stop rules (with [L] ). 如果存在,请不要更改文件名和停止规则(使用[L] )。 If it doesn't exist, rewrite the file name back to what it was and continue with the rules you already have. 如果不存在,请将文件名改写回原来的名称,然后继续使用已有的规则。

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

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