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]

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.

2 thoughts 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.

  2. mvaneijgen says:

    I would love to use this, but I just can’t get it to work. My current `.htacces` file looks like this.
    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /things/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /things/index.php [L]

    # END WordPress

    and my local domain is `http://localhost:3000/things/` and the remote domain looks like this `http://domain.nl/things/` What lines should I rename and which to replace? My local server is running on AMPPS (if that makes any difference) and `things` is the current site I am working on.

Comments are closed.