How to Load Images from Live Site in Local Dev (Apache and Nginx)

I just got a neat trick for local development.

When cloning live site to local, we need to download all the assets/uploads directory to our local dev, and sometimes it’s a pain.

With this trick, we don’t need to do that and we can simply download the DB.

The idea is to load files from live site if the file is lot found in local site. This tricks also useful if we want to create staging dev/clone the site temporarily.

This code will load not only images but also other assets such as CSS, JS, etc.

Apache:

In apache server, we can drop this code in .htaccess before WordPress generated rule.

# Use live site assets.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteCond %{HTTP_HOST} ^yourlocaldomain\.local$
RewriteRule ^(.*\.(js|css|png|jpe?g|gif|ico)) http://yourlivesite.com/$1 [L,R=302,NC]
</IfModule>

So, in the code above your local site domain is yourlocaldomain.local and your live site is yourlivesite.com

Nginx:

For nginx, you can add this code in your nginx configuration file (something with .conf)

location ~* .(js|css|png|jpg|jpeg|gif|ico|mp3|mov|tif|tiff|swf|txt|html)$ {
    expires 24h;
    log_not_found off;
    try_files $uri $uri/ @production;
}

location @production {
    resolver 8.8.8.8;
    proxy_pass http://yourlivesite.com/$uri;
}

You will need to add it in server block in your site conf. So it will look something like:

server {
    location ~* .(js|css|png|jpg|jpeg|gif|ico|mp3|mov|tif|tiff|swf|txt|html)$ {
        expires 24h;
        log_not_found off;
        try_files $uri $uri/ @production;
    }

    location @production {
        resolver 8.8.8.8;
        proxy_pass http://yourlivesite.com/$uri;
    }
}

And after that, you will need to restart/reload nginx using this command in terminal:

sudo service nginx restart

And that’s it.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.