Search code examples
djangonginxwebserver

Serving static and media files on a distant server with Django and Nginx


I am configuring a server with Nginx that redirect subdomains to websites (made with Django) on distant servers (on the same local network). It is working fine to serve the content of each site, but I have trouble to serve static and media files (for instance css). Here is the content of the configuration file :

server {
            listen 80;
            server_name myaddress.fr

            location / {
                    proxy_pass              http://192.168.0.85:8000;
            }
}

And here is the end of settings.py in the Django website (which listen at 192.168.0.85:8000) :

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'


MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'

Usually, when my websites are on the same server than nginx, I just have to add these lines to the nginx conf file:

location /media/  {
    alias /local/path/to/media/;
}

location /static/ {
    alias /local/path/to/static/;
}

How can I generalize this config to serve media and static files on a distant server (here at 192.168.0.85)? Should I install another webserver on the distant machine?

Thanks in advance for your help!


Solution

  • You need some way of providing a route to show those files.

    One way of doing so would be to install nginx on the remote servers and proxy to it just as you do with the app itself.

    An alternative, since you say this is all within the same local network. would be to use something like NFS to mount the static directories onto the proxy server, so that the existing nginx could serve them directly.

    A similar option would be to configure the staticfiles app, as well as the storage of user-uploaded files, to save their files directly on the proxy.