Safely Using Production Assets in Staging

There are well over 100GB of image assets in the production deployment of the Web app I am currently developing. Since I’m using a full dump from the production database for my staging database, I need my staging environment to use all the same assets as well. The last thing I want to do is to copy the 100GB+ of images into my staging environment.

Simply sharing the assets between production and staging sounds easy, but there are caveats. I have to make sure that anything I do in staging (for example, deleting image assets) does not affect the production environment. To achieve this, I added this hack to my staging nginx config:

# Concatenate results of following if statements
set $image_hack "";

# Mark if an image is requested
if ($request_filename ~* .(css|jpg|gif|png)$) {
  set $image_hack I;
}

# Mark if the static file is not found
if (!-f $request_filename) {
  set $image_hack "${image_hack}F";
}

# If the request is for an image that is not found, redirect to production
if ($image_hack = IF) {
  rewrite ^/(.*) http://production.mysite.com/$1 permanent;
  break;
}

This admittedly seems like a lot of code, but nginx seems to lack the ability to conditionally test if (this AND that). With this hack in place, any CRUD actions on assets will be performed locally, while requested images first be found locally, then proxied to production.