开发者

RewriteRule with file check and resize image

I currently have this folder structure:

img.domain.com/
    boats/
        boat1/
            1.jpg
            2.jpg
    trees/
        tree1/
            1.jpg
        开发者_Python百科    2.jpg

I already have a PHP script on img.domain.com/index.php that resizes the image and a RewriteRule that let me access the image (resizing or not) this way: img.domain.com/boats/boat1/1/200/200/a-big-boat.jpg

For this I'm using:

RewriteRule ([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)\.([^/]+) index.php?folder=$1&id=$2&file=$3&ext=$7&w=$4&h=$5&description=$6 [NC]

This is all working good.

What I want is, after creating the cached image with PHP, access it if it exists, but only using a RewriteRule. I don't want to check for the file with PHP.

I read this question (Best way to cache resized images using PHP and MySQL) that has a pretty good solution:

RewriteCond %{REQUEST_URI} ^/images/cached/
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule (.*) /images/generate.php?$1 [L]

But I can't adapt to my case.

Any ideas?


I found the solution for my own question.

First, the PHP script has to create the cached file exactly where the URL points. This means, after resizing the image, save it on that path.

In the example I gave: img.domain.com/boats/boat1/1/200/200/a-big-boat.jpg (that doesn't exist on the first time it is called) will save an image on that path (img.domain.com/boats/boat1/1/200/200/) with name a-big-boat.jpg and size of 200x200.

Now, the .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)\.([^/]+) index.php?folder=$1&id=$2&file=$3&ext=$7&w=$4&h=$5&description=$6 [NC]

It will request the image and if does not exist, call index.php with those parameters and create the cache. Next time, it will get the cached file without passing through the index.php. This (.htaccess) is better than checking if file exists with PHP.

Of course, the RewriteRule is for my case only.

And tweaking just to avoid listing if user try to access something like img.domain.com/boats/1/200/ or any other folder created by the cache system. Put this as first rewrite condition.

RewriteCond %{REQUEST_FILENAME} -d
ErrorDocument 403 /forbidden.php

Warning! Be careful with size and the file name. In my case, as the final file name (a-big-boat.jpg) isn't the same as the original (1.jpg), users can create infinite cache files just changing the final name. The same for the size.

Check the size requested against the standard sizes set by you. As for the name, I will get an unique name from database. This will check the DB only once per image/size and never check again after cached, so it is not a problem. If the name is correct, create the cache, if not send to "image not found".

I hope this can help other people.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜