简体   繁体   中英

Serving static files from nginx with django + fastcgi debian

I'm a little rusty when it comes to the new way of static file serving with django 1.3 however I'm sure it cannot be django that is at fault here.

I'm trying to run a django app with nginx + fastcgi on a cloud server with debian installed. We only have one server at the moment (while we develop) and will be looking to run multiple servers with a load balancer to make this a little simpler however I'm having trouble actually getting nginx to serve static files.

I've followed various tutorials for setting up nginx.conf to serve the files

server {
    listen 80;
    server_name 127.0.0.1;

    location /static  {
        autoindex on;
        root /static;
    }
}

The above is an extract from nginx.conf. Now no matter what I set root to, nginx throws a 404 not found error when trying to access http://127.0.0.1/static/ .

The file structure is as follows:

/home/user/site/project
/home/user/site/static
/home/user/site/templates

Django settings.py has the following set up as STATIC_ROOT and STATIC_URL

STATIC_ROOT = "/home/user/site/static/"
STATIC_URL  = "http://127.0.0.1/static/"

If anyone could point us in the right direction of where to do with this it would be fantastic.

root /static

Shouldn't this be /home/user/site/static instead?

Check the difference between using ' root ' or ' alias '. Basically in case of using 'root' the path next to 'location' (/static/) gets appended in path, while in case of 'alias' it'll be ignored.

Resolution found, based on Jim's answer above.

root /static 

Has now been changed to:

root /home/user/site/static

However then checking the logs it seems that the path nginx was trying to locate at http://127.0.0.1/static was /home/user/site/static/static/ which is evidently incorrect.

I'm unsure if this is the correct method however i'm now pointing all static files into root (removing the need for /static in the url. so for /static/images I now just point it to http://127.0.0.1/images/ .

Check out the documentation of the root directive, in contrast to Apache's alias directive, the location match is not dropped. So when you specify a location static the folder you define as your root must contain the static folder. So it's not wrong that nginx is looking for /home/user/site/static/static it is intentional behavior.

I would even prefer using http://host/static/images as your URL for serving static images. This way it follows the Django documentation Managing static files which suggests to use a prefix for you static files. Otherwise you have multiple folders for different static content cluttering your project and app folders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM