WordPress and it's horrible media management: how to add a cache folder for resized images

Code snippet to move all auto-resized images to a cache folder.

I've been fighting the media "management" in WordPress for years and I still couldn't get over the fact that the downsized images all go into the same folder as the uploads. In case you take backups of you site who'd want the downsized images?! That's redundancy as they can easily be regenerated.

The problem is that currently the downsized media functions can't be filtered the way they should be, so I ended up moving all the intermediate sized images to a cache folder and add a symlink to the original location; the following code therefore will work only if the WordPress is hosted on a linux server.

The PHP part

The code was removed from here, and was given it's own plugin and repository. Please visit wp-resized2cache.

The nginx hack

Besides the plugin, it also requires some magic in nginx; that is to try to locate the files in the cache folder first.

location ~ "^/files/(.*)$" {
    try_files $uri /wp-content/cache/$1 @filesrewrite;

location @filesrewrite {
    rewrite ^/files(.*) /wp-content/files$1 last;