1

I am running a django with nginx as a web server. After configuration its seems that I am always getting 404 for static files. Here is my configurtaion

base.py

STATIC_ROOT = os.path.join(PROJECT_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static_files'),
]

nginx.conf

    upstream django {
        server unix:///tmp/mysite.sock;
    }


    # configuration of the server
    server {
        listen  5000;
        server_name server localhost:5000;  address or FQDN
        charset     utf-8;
        client_max_body_size 75M;   

      location /static {
        alias /Users/del/projects/app-backend/static/; 
      }

      location ~ ^/(images|javascript|js|css|flash|media|static)/  {
        autoindex on;
        root /Users/del/projects/app-backend/static/; 
      }

      location / {
        uwsgi_pass  django;
        include     /Users/del/perso/django/library/uwsgi;

       } 
    }

I have made sure to run python manage.py collectstatic, and the files are actually generated under /static/ folder

2
  • did you used collectstatic? Commented Jun 30, 2017 at 16:00
  • yes, i did and i have already written that in my question. Commented Jul 3, 2017 at 13:04

1 Answer 1

2

You seem to have guessed what should work for nginx, but don't understand how alias and root work:

root sets the parent directory for the location. A physical directory with the same name must exist in the parent directory:

root    /var/www
directory     |----- /static
file                    |----- image.jpg

location /static with root /var/www will now serve files from /var/www/static. The URL http://example.com/static/image.jpg will serve /var/www/static/image.jpg.

Same structure, but location /s with alias /var/www/static will now serve files from /var/www/static. The URL http://example.com/s/image.jpg will serve /var/www/static/image.jpg.

So your simple config would be:

server {
    root /var/www; # Set root at server level

    location /static {
        expires max;
    }

    location / {
        uwsgi_pass django;
    }
 }

I don't know what you need the regex for. If you use Django's static tag in your templates consistently, there is no need to match "/images" and so forth.

And finally, since static is in the regex and regex patterns have priority over string matches, all your references to /static/ in the URL are being looked for in app-backend/static/static.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.