开发者

htaccess: Check if a file exists based on variables

开发者 https://www.devze.com 2023-03-12 00:09 出处:网络
I am writing a on-the-fly thumbnail creator for a CMS and need to dynamically check if a file exists. I currently have created an htaccess file that checks if the file you are requesting exists, but n

I am writing a on-the-fly thumbnail creator for a CMS and need to dynamically check if a file exists. I currently have created an htaccess file that checks if the file you are requesting exists, but need it to be a bit more advanced and "create" the file check based on the submitted URLs options.

Here i开发者_如何学Gos what I currently have (based on image ID, not name):

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]

Based on this URL:

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

An htaccess file checks if this file exists:

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

If it doesn't exists it RewriteRules user to:

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

"Crop" is optional, so without it the previous URLs look like this:

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

Basically, I need the RewriteCond to check if a file exists based on a filename that it creates based on the REQUEST_FILENAME. Any ideas?

Something like this:

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

Not even sure if this is possible... in which case I would have it forward ALL requests to the PHP file, but since the PHP has a lot of overhead I thought this would be speedier.

Thank you very much for any help in advance!


from the rewritecond docs

RewriteRule backreferences: These are backreferences of the form $N (0 <= N <= 9), which provide access to the grouped parts (in parentheses) of the pattern, from the RewriteRule which is subject to the current set of RewriteCond conditions..

RewriteCond backreferences: These are backreferences of the form %N (1 <= N <= 9), which provide access to the grouped parts (again, in parentheses) of the pattern, from the last matched RewriteCond in the current set of conditions.

# 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
0

精彩评论

暂无评论...
验证码 换一张
取 消