/ wordpress

How to rewrite uploads to production from your local WordPress environment

WordPress sites have a lot of media files, and over time we are just uploading more and more media which get bigger as we demand more quality and higher resolutions for pictures being displayed on super ultra definition high dpi mega screens. This makes for great web browsing experiences, but poor developer local environment experiences! :(

However when a developer needs to clone this site locally we now have some decisions to make. We can just deal with the media not existing locally, or copy the entire media library down to our local machines. I like to test sites accurately, but I also don't want to have to copy all your pictures and waste hard drive space!

A few years ago I shared this Gist, which mass redirected all media back to the live site. Rejoice! Your local hard drive space was spared and your local WordPress environments looked like production thanks to loading the original media files! There was one problem though, now when you tried to upload files locally the file existed locally and was still redirected to production. Leaving you with more broken images.

No more.

With the latest iteration of my Nginx redirect for WordPress media libraries, you can redirect missing files to production, and keep uploading files locally without breaking them.

Just drop this little snippet into your site's Nginx configuration, and update the production site's URL.

location ~ ^/wp-content/uploads/(.*) {
    if (!-e $request_filename){
        rewrite ^/wp-content/uploads/(.*)$ https://yoursite.com/wp-content/uploads/$1 redirect;
    }
}

I'm sure there are ways to make this more elegant than it is now, I am not a Nginx configuration expert. However this is not built for scale or performance, this is built for our local development environments. So, things like "if statements are bad for Nginx" don't bother me.

This post is simply my attempt at testing out the code blocks of Koenig, the new block/card based editor for Ghost. Hope you enjoyed it!

Patrick Garman

Patrick Garman

Web application development extraordinaire, e-commerce scaling expert, and an ok public speaker. Partner @ Mindsize.

Read More
How to rewrite uploads to production from your local WordPress environment
Share this

Subscribe to Patrick Garman