Avoid Syncing wp-content/uploads
If you've ever done any WordPress development (specifically long-term maintenance), you will know that it is tedious to keep your local environment up-to-date with the wp-content/uploads folder.
This folder, as you may already know, is the destination for any asset uploaded via the WordPress admin interface. As a WordPress site matures, content editors will be uploading megs and megs of images, and, in some cases, I have seen the media library grow to sizes more easily measured in Gigabytes! Many of these images are embedded in the content of WordPress posts and pages. So if you ever pull down a copy of the live database for use with local development, you will see a lot of broken images. Of course, you could simply download the entire folder using scp
or rsync
, but there is a better way.
Proxy wp-content/uploads
Placing the following snippet in an .htaccess file in the wp-content/uploads folder on your local server will proxy requests to the remote server.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} dev.example.com # Only perform the proxy on dev site
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) http://www.example.com/wp-content/uploads/$1 [L,P]
</IfModule>
Notice the first line of our rewrite condition (the one that references HTTP_HOST), which protects our production servers if this .htaccess file is accidentally deployed live.
You must have modproxy enabled for this to work. In Ubuntu, the command `sudo a2enmod proxy proxyhttpfollowed by a
sudo apache2ctl restart` will do the trick.
Conclusion
Using this method will save you time and bandwidth. Although I haven't tested it extensively, I plan to use it on all of my future WordPress projects.
Written by Franklin Strube
Related protips
3 Responses
Great idea!
Does it work on a subdomain - multisite install?
For Wordpress multisite / subdomain install :
RewriteCond %{HTTP_HOST} domain1.multisite-install.com
RewriteRule (.*) http://www.domain1.com/wp-content/uploads/$1 [L,P]
RewriteCond %{HTTP_HOST} domain2.multisite-install.com
RewriteRule (.*) http://www.domain2.com/wp-content/uploads/$1 [L,P]
and so on...
:D
I don't know why, but I needed to include sudo a2enmod rewrite proxy proxy_http ssl proxy_balancer
and then it worked, but what a great trick! I also added it directly to my dev server apache .conf file so it will never make it into production.