Nginx static files from multiple static sources

I have a Django application running on Gunicorn. I am trying to configure Nginx to serve static files. I have two upstream servers, they come from two different directories, and two different Gunicorn instances. Usually, it is the same code in both folders, but when I need to update the code, I will take one of the Gunicorn instance offline, so that Nginx stops routing traffic to that instance, update the code, and turn Gunicorn back on.

There are two static directories (on from the primary Gunicorn instance, one from the secondary). When I do an update on, let’s say the primary, traffic is no longer routed to the primary, and I don’t want Nginx to serve static files from the primary static directory.

How can I configure Nginx to do that? Basically, I want two static roots, one linked to each upstream server.

Answer

I’m not aware of a way to do this automatically in an Nginx instance as your talking about a routing decision that is made behind the static file serving. Maybe if Nginx exposes some environment information from the overall proxy/routing service not related to the current request?? The variables mentioned look to be populated post routing though.

Otherwise I can think of two options. You could have multiple nginx configs files: dual config, primary config, secondary config

N/NP/NS
 /  \ 
GP   GS

When you want to change the topology, copy the config (or have a script to modify it) into place and reconfigure.

Alternatively you could run two Nginx instances (primary, secondary) servers each configured with their appropriate static directories and gunicorn instances. Then control the traffic via the primary/secondary Nginx during the releases rather than via Gunicorn.

   N
 /   \
NP   NS
|     |
GP   GS

You still need something out the front like an nginx instance, load balancer or DNS traffic management to direct/control traffic to your two web servers.

Attribution
Source : Link , Question Author : Flavien , Answer Author : Matt

Leave a Comment