开发者

Dynamically serving files depending on whether they're written to file system

Terrible title, but don't really know how to describe the situation too well. I would like to dynamically resize/crop images. I'm hoping to co开发者_StackOverflow社区nfig my apache to do the following:

  • A request for /img/profile.jpg?crop&p=50 is received
  • Apache checks if the file /img/profile.c.50.jpg exists
  • If it does exist, it serves that up statically without having to hit my php server
  • If it doesn't exist, it hits /cropper.php?path=/img/profile.jpg&p=50
  • This file then writes the image to file, and serves it
  • Request comes in again (see step 1)

I feel like making use of the FilesMatch directive in the .htaccess file could be of us but I really don't know where to start. Any links would be appreciated, or any ideas.

Thanks all.


\Personally, I'd delegate this task to a script (maybe using X-Sendfile), rather than a rewrite mess.

Here you go, you may have to tweak your document root and make your "profile" part more general:

RewriteEngine on
RewriteCond %{QUERY_STRING} "(?:^|&)crop&p=50"
RewriteCond %{REQUEST_URI} ^(/img/profile)(\.png)$
RewriteCond /your/document/root%1.c.50%2 -f
RewriteRule ^ %1.c.50%2 [L]

# hand over to crop script if the above doesn't match
RewriteCond %{REQUEST_URI} =/img/profile.png
RewriteRule ^ /cropper.php?path=%{REQUEST_URI}&p=50 [L]

Solution always involving a script: (accessed through /img/profiles/... for clarity)

  • $1 captures the profile name (in this case assumed to be 'a-z' only
  • $2 captures the desired width
  • $3 the file extension

Which really simplifies the rewrite:

RewriteEngine on
RewriteRule ^/img/profiles/([a-z]+)\.([1-9][0-9]+)\.(jpe?g|gif|png)$ /cropper.php?profile=$1.$3&p=$2 [L]

The script would check whether the file exists and either deliver it or generate it first.

Solution taking the image name from the requested URL:

(As you mentionned in your comment)

RewriteEngine on
RewriteCond %{REQUEST_URI} ^(/img/profile)\.([1-9][0-9]+)\.(png|gif|jpe?g)$
RewriteCond /your/document/root%{REQUEST_URI} -f
RewriteRule ^ %{REQUEST_URI} [L]

# hand over to crop script if the above doesn't match
RewriteCond %{REQUEST_URI} ^(/img/profile)\.([1-9][0-9]+)\.(png|gif|jpe?g)$
RewriteRule ^ /cropper.php?path=$1.$3&p=$2 [L]

which may be rewritten to the following, if the images are stored directly within your document root:

RewriteCond %{REQUEST_URI} ^(/img/profile)\.([1-9][0-9]+)\.(png|gif|jpe?g)$
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^ /cropper.php?path=$1.$3&p=$2 [L]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜