Joe Lencioni
Joe Lencioni

Reputation: 10511

mod_rewrite to serve static cached files if they exist and if the source file hasn't changed

I am working on a project that processes images, saves the processed images in a cache, and outputs the processed image to the client. Lets say that the project is located in /project/, the cache is located in /project/cache/, and the source images are located wherever else on the server (like in /images/ or /otherproject/images/). I can set up the cache to mirror the path to the source image (e.g. if the source image is /images/image.jpg, the cache for that image could be /project/cache/images/image.jpg), and the requests to the project are roughly /project/path/to/image (e.g. /project/images/image.jpg).

I would like to serve the images from the cache, if they exist, as efficiently as possible. However, I also want to be able to check to see if the source image has changed since the cached image was created. Ideally, this would all be done with mod_rewrite so PHP wouldn't need to be used to do any of the work.

Is this possible? What would the mod_rewrite rules need to be for this to work?

Alternatively, it seems like it would be a fine compromise to have mod_rewrite serve the cached file most of the time but send 1 out of X requests to the PHP script for files that are cached. Is this possible?

Upvotes: 1

Views: 768

Answers (2)

Roland Illig
Roland Illig

Reputation: 41617

You cannot acces the file modification timestamp from the RewriteRule, so there is no way around using PHP or another programming language for that task.

On the other hand this is really simple in PHP, so you should first check whether the PHP solution is good enough in you case. Only if it isn't you should look for alternatives.

Upvotes: 1

Detect
Detect

Reputation: 2069

What if you used the client to do some of the work? Say you display an image in the web browser and always use src="/cache/images/foobar.jpg" and add an onerror="this.src='/images/foobar.jpg'". In mod_rewrite, send anything that goes to the /images/ dir to a script that will return and generate an image in the cache.

Upvotes: 0

Related Questions