How to serve django media files via nginx ?

iva123 picture iva123 · Dec 3, 2011 · Viewed 23.9k times · Source

I'm new at Nginx, I've successfully bound my django project to Nginx. However I can't serve my static files and I guess I set my media folder's location wrongly. Here is my file tree:

root_directory
     my_django_project
         ...
         manage.py
         app1
         app2
         media
           admin
           css
           js
           ...

And my nginx.conf goes like :

        server {
                listen 192.168.1.9:80;
                server_name localhost;
                # site_media - folder in uri for static files                                                                                                

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

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov) {
  access_log   off; # po co mi logi obrazków :)                                                                                                              
  expires      30d;
}
                location / {
                        # host and port to fastcgi server                                                                                                    
                        fastcgi_pass 127.0.0.1:8080;
            fastcgi_param PATH_INFO $fastcgi_script_name;
                        fastcgi_param REQUEST_METHOD $request_method;
                        fastcgi_param QUERY_STRING $query_string;
                        fastcgi_param CONTENT_TYPE $content_type;
                        fastcgi_param CONTENT_LENGTH $content_length;
            fastcgi_pass_header Authorization;
                        fastcgi_intercept_errors off;
                        }
                access_log      /var/log/nginx/localhost.access_log main;
                error_log       /var/log/nginx/localhost.error_log;
        }
}

When I open my admin page, all css pages give 404 error. Can you tell me that how can I set my media path correctly ?

Answer

j_syk picture j_syk · Dec 5, 2011

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.