htaccess:根据变量检查文件是不是存在

Posted

技术标签:

【中文标题】htaccess:根据变量检查文件是不是存在【英文标题】:htaccess: Check if a file exists based on variableshtaccess:根据变量检查文件是否存在 【发布时间】:2011-09-11 23:33:39 【问题描述】:

我正在为 CMS 编写动态缩略图创建器,需要动态检查文件是否存在。我目前创建了一个 htaccess 文件,用于检查您请求的文件是否存在,但需要更高级一些,并根据提交的 URL 选项“创建”文件检查。

这是我目前拥有的(基于图像 ID,而不是名称):

RewriteEngine on

#Check for file existence here and forward if exists
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteRule ^([0-9]+)-([0-9]+)-([0-9]+)(-(crop))?\.jpg$ thumbnail.php?id=$1&w=$2&h=$3&c=$4 [L,QSA]

基于此网址:

this-is-the-image-name.gif?w=200&h=100&c=true

一个 htaccess 文件检查这个文件是否存在:

this-is-the-image-name-gif-200-100-crop.jpg

如果它不存在,则 RewriteRules 用户:

thumbnail.php?name=this-is-the-image-name&type=gif&w=200&height=100&c=true

“裁剪”是可选的,所以没有它之前的 URL 看起来像这样:

this-is-the-image-name.gif?w=200&h=100
this-is-the-image-name-gif-200-100.jpg
thumbnail.php?name=this-is-the-image-name&type=gif&w=200&height=100

基本上,我需要 RewriteCond 根据它基于REQUEST_FILENAME 创建的文件名检查文件是否存在。有什么想法吗?

类似这样的:

RewriteCond ^([a-zA-Z0-9-]+).(jpg|gif|png)?w=([0-9]+)&h=([0-9]+)(&c=(-crop))?\.jpg$ %$1-$2-$3-$4-$6.jpg !-f

甚至不确定这是否可能......在这种情况下,我会让它将所有请求转发到 PHP 文件,但由于 PHP 有很多开销,我认为这会更快。

非常感谢您提前提供的任何帮助!

【问题讨论】:

【参考方案1】:

来自 rewritecond 文档

RewriteRule 反向引用:这些是 $N (0

重写条件 反向引用:这些是 %N (1

# file is a gif
RewriteCond %REQUEST_FILENAME .gif$

# capture the and params in () backreferences
RewriteCond %QUERY_STRING w=(200)&h=(100)&c=true

# only rewrites for files that do not exist
RewriteCond %REQUEST_FILENAME-gif-%1-%2-crop.jpg !-f

# this rewrites not found thumbs to your php script
RewriteRule %.*$ thumbnail.php?name=%REQUEST_FILENAME&type=gif&w=%1&height=%2&c=true

【讨论】:

这正是我想要的。当我导航到:this-is-the-image-name.gif?w=200&h=100&c=true 时,它目前似乎没有转发,而是说:Not Found: The requested URL /dev/media/thumbnails/this-is-the-image-name.gif was not found on this server.。虽然没有收到内部服务器错误,所以它似乎是正确的语法。 忘记在评论中标记你的句柄 ;) 所以这似乎是有效的,除了规则规定只使用来自 last RewriteCond 的反向引用......因为文件并不总是一个 gif (jpg |gif|png) 我需要找到一种方法来保存第一个 RewriteCond 中的文件类型。我还把REQUEST_FILENAME 换成了REQUEST_BASENAME...

以上是关于htaccess:根据变量检查文件是不是存在的主要内容,如果未能解决你的问题,请参考以下文章

如何根据 PL/SQL 变量值检查输入参数值是不是存在作为列表?

检查文件是不是来自 htaccess / Apache

htaccess 删除参数和索引文件

如何根据本地 ivy 文件检查 Artifactory 中是不是存在工件

HTA (VBScript) - Shell.Run 使用变量

JavaScript - 检查变量是不是存在[重复]