[Django]-How to serve django media files via nginx ?

78👍

Here’s a example of how I have my nginx servers setup

server {
    server_name example.com www.example.com;
    location /static {
        autoindex on;
        alias /home/myusername/myproject/static/;
    }
    location /media {
        autoindex on;
        alias /home/myusername/myproject/media/;
    }
    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}

I serve django with Gunicorn on localhost port 8000. (that’s what the proxy_pass is for)

The Nginx wiki example configuration may help you too. Notice in their static file serving they specify allowed filetypes and use ‘root’ instead of ‘alias’ but they are similar.

This ServerFault question may help.

👤j_syk

2👍

You have set this:

location /media/  {
    root /home/nazmi/workspace/portal/media/;                                                                                       
}

This means that the location will be xxx/media/media. Nginx will go to […]/portal/media and look for a folder called media.
It should rather be like this:

location /media/  {
    root /home/nazmi/workspace/portal;                                                                                       
}

Also you should remove the trailing slash.

1👍

If the media file isn’t serving, try to set media location as below in the conf file inside the sites-enabled directory. This works for me.

location /media {
    root /home/username/projectname/;

0👍

The following code works for me:

server {
    server_name example.com www.example.com;
    location /static {
        autoindex on;
        **alias /home/myusername/myproject/;**
    }
    location /media {
        autoindex on;
        **alias /home/myusername/myproject/;**
    }
    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}

I bold the different parts according to the previous answer.

👤smrf

0👍

location /media  {
     alias /home/user/django_app/media; #(locaion of your media folder)                                                                                       
}

Try this code in nginx config to serve static and media files for a django applications (without autoindex on settings)

👤Nijo

Leave a comment