Production images in local environment with nginx
One of the most common and useful processes when developing a new website is the creation of multiple work environments to ensure that our changes or new features work perfectly before even approaching production.
At the same time, one of the most common problems in these cases is the disconnect between new environments, it is not uncommon to have 3 different databases between local, staging, and production.
Ideally, each of these environments should be an exact copy of production, having the same “server” (or at least something as close as possible), the same database, and in increasingly common cases, the same multimedia files.
The problem
While for the database, or servers, it is not so much of a problem to receive a copy that we can use in our local system, multimedia files generally have a much larger size, and therefore sometimes result in a loss of space by having several copies of the same file for each of our environments, especially with images that many systems crop, creating more and more copies of the same image.
The solution
The solution in these cases is actually quite simple, all we need to do is: use our production files in our local environment.
The steps for this may vary, but in my case, I usually use nginx, and the steps
for this are to find the configuration file (usually default.conf
or site.conf
).
Within this file, we will add a location
tag, so that it looks like this example:
1# Basic conf2server {3 server_name _;4 return 302 $scheme://mysite.test$request_uri;5}67# Custom conf89server {10server_name ~^(.\*)\.mysite\.test$ mysite.test;11root /app/public/;1213 # If file ends with these extensions14 location ~* ^.+\.(svg|svgz|jpg|jpeg|gif|png|ico|bmp|webp)$ {15 try_files $uri @image_fallback; # Try this address (defined below)16 }1718 # Define URL to try (prod url)19 location @image_fallback {20 proxy_pass https://mysite.com;21 }2223 # More default conf...24 index index.php index.html index.htm;25 include do-not-modify/*.conf;2627}28
Now, every time my server receives a request to one of the files I have defined, instead of looking for them on my local server, it will look for them on my production server, giving me the real image I have in production without the need to copy it locally.