Managing WordPress Uploads While Developing Locally NGINX
I've worked on my fair share of large existing WordPress sites that contain several gigabytes worth of uploads. Upload volume of this size (or even larger) can make managing your local dev environment a pain. You either have to download the entire uploads directory, which is time consuming and redundant, or figure out a way to redirect image requests to a remote server (better solution).
I did the former for year until finally I took a few minutes to find a better solution. There are many examples out there using rewrite rules or WordPress hooks to solve this problem but I found they didn't solve my issue. Either filtering fails to target images embedded within the editor (for example: the filter wp_get_attachment_image_src
only works on images fetched with WP functions such as wp_get_attachment_image()
) or the rewrites are intended for use in .htaccess ( Apache server). For local development I’ve adopted Varying Vagrant Vagrants which uses NGNIX so .htaccess isn't used and as mentioned before wp_get_attachment_image_src
won't get all the images.
While I could find NGINX examples of how to redirect uploads to remote and VVV has pretty documentation on their site for modifying the default config I was still a little lost.
Each site in VVV is provisioned with a vvv-nginx-default.conf file inside ~/vagrant-local/www/{sitename]/provision/
. To create modifications for a specific site clone vvv-nginx-default.conf
to vvv-nginx-custom.conf
. Now you can make modifications as needed, for your modifications to take effect you’ll need to run vagrant reload –provision
. Below is my custom conf file with the redirect for uploads. Very simple but it took me a bit to figure out how to implement specially for VVV. Hope it helps someone out there.
server {
listen 80;
listen 443 ssl http2;
server_name {vvv_hosts};
root {vvv_path_to_site}/public_html;
# Nginx logs
error_log {vvv_path_to_site}/log/nginx-error.log;
access_log {vvv_path_to_site}/log/nginx-access.log;
# This is needed to set the PHP being used
set $upstream {upstream};
# Enable server push if SSL/HTTP2 is being used for link preload headers
http2_push_preload on;
{vvv_tls_cert}
{vvv_tls_key}
# Nginx rules for WordPress, rewrite rules, permalinks, etc
include /etc/nginx/nginx-wp-common.conf;
{LIVE_URL}
# WP uploads redirect to production
location ~ ^/wp-content/uploads/(.*) {
if (!-e $request_filename){
rewrite ^/wp-content/uploads/(.*)$ https://example.com/wp-content/uploads/$1 redirect;
}
}
}