Loading missing images from a remote server

When developing on a local server it can be painful to keep images in your media library synced with your production site. Sure, you could download the missing images and attachments to your local machine every time you need to work on the site, but this approach has two problems:

  1. It is time consuming
  2. The files take up space on your local drive

I recently discovered a way to seamlessly handle missing images so that they never 404 or occupy space on your local machine. The solution is an htaccess rewrite rule that checks if an image exists locally, and if it doesn’t, attempts to load it from your production server.

Here is a sample htaccess directive for WordPress:

# Load media files from production server if they don't exist locally
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{HTTP_HOST} ^localsite\.dev$
  RewriteRule ^wp-content/uploads/(.*)$ http://remotesite.com/wp-content/uploads/$1 [NC,L]
</IfModule>

Remember to change “remotesite.com” and “localsite.dev” in the example to match your own domain, and adjust your file paths as necessary. If you’re implementing this on a WordPress site make sure to place it before WordPress’ own htaccess directive.

Hat tip to @stevegrunwell for bringing this technique to my attention.

One thought on “Loading missing images from a remote server

  1. Ian Pegg says:

    This is brilliant! Thanks, Jonathan.

    I started off with Steve Grunwell’s rules but needed something that would only swing into action on my local machine. Ideally, I’d love it if I could place these rules into a .htaccess above public_html and then just add that file to my .gitignore so it remains on local.

    One thing that had me fooled for a bit — if you’re using Cloudflare or a similar service with your live site, make sure Hotlink Protection is turned off or else the requests from your local machine will return a 403.

Leave a Reply

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