Fallback Images

When working on a website, I always develop locally – usually using Varying Vagrant Vagrants. I’ll often times pull down a copy of the production database and do a search and replace to make sure I’m dealing with local urls, so that I have some real content to develop with. This works great, except for a bunch of annoying missing images. I could download all the images from the server, but who wants all those files on their computer? I don’t.

My solution to this was to have nginx serve the images from the original server, if they are not present locally. It seems to be working great so far, and all it took was a few extra lines in the nginx config.

location ~* ^.+\.(svg|svgz|jpg|jpeg|gif|png|ico|bmp)$ {
    try_files $uri @image_fallback;

location @image_fallback {
    proxy_pass http://example.com;

For any .jpg, .gif, or .png file, nginx first tries to find the file locally. If its not there, it passes it along to example.com and tries to find it there. This could probably be expanded to try and get other file types as well, but at the time, I only needed these image types.

4 thoughts on “Fallback Images

  1. I used this solution recently and found that it worked, except for some of the site’s images were served through an AWS instance, and those ones were coming through broken.

    try_files takes only one argument, so you can’t simply add more servers to check. However, I found that you can daisy-chain more servers on by catching 404 errors.

    My code – https://pastebin.com/U9eVghMR

    I found the solution here – http://linuxplayer.org/2013/06/nginx-try-files-on-multiple-named-location-or-server

Leave a Reply

Your email address will not be published. Required fields are marked *