如何通过nginx提供静态文件?

时间:2015-01-20 05:58:50

标签: django nginx

静态文件无法通过nginx提供。我没有找到这个问题的答案,所以请帮我弄明白。

settings.py

DEBUG = False

/etc/nginx/sites-available/example.com

upstream test {
        server 127.0.0.1:8000;
        keepalive 500;
}

server {

    listen   80;
    server_name example.com;

    client_max_body_size 4G; 
    location /static/ {
       alias   /home/user/live/staticfiles/;
   }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $http_host;

        proxy_redirect off;
             proxy_pass http://test;

    }

}

cat /var/log/nginx/error.log 向我显示输出

 2015/01/20 05:43:07 [error] 4480#0: *7 open() "/home/user/live/staticfiles/images/footer-logo.png" failed (13: Permission denied), client: 182.74.206.202, server: example.com, request: "GET /static/images/footer-logo.png HTTP/1.1", host: "example.com", referrer: "example.com/"

更新:

我只是说它不能正常工作......由于文件权限问题,我仍然无法相信这种情况。我在下面详细介绍了......

[myuserm@instance-4 home]$ namei -om /home/myuser/live/staticfiles/js/jquery.fancybox.js
f: /home/myuser/live/staticfiles/js/jquery.fancybox.js
 dr-xr-xr-x root          root          /
 drwxr-xr-x root          root          home
 drwxrwxrwx myuser        myuser        myuser
 drwxrwxrwx root          root          live
 drwxrwxrwx myuser        myuser        staticfiles
 drwxrwxrwx myuser        myuser        js
 -rwxrwxrwx myuser        myuser        jquery.fancybox.js

1 个答案:

答案 0 :(得分:0)

首先,检查您的设置是否应该看起来像这个设置的静态文件

STATIC_ROOT =  "/home/user/live/collected_static/"
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    PROJECT_DIR.child("static"),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
  

然后你运行./manage.py collectstatic#这将收集所有静态   文件到gather_static文件夹,

然后在你的nginx设置中:

location /static {
    alias /home/user/live/collected_static/; 
}

   location / {

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://test;
            break;
        }
    }

希望这会解决您的问题。我们也应该像django项目代码一样检查权限。无需提供任何额外的许可。

有关更多设置和非常好的文档,请查看此处:Setting up Django with Nginx, Gunicorn, virtualenv, supervisor and PostgreSQL

对于nginx权限问题,您可以从以下链接找到解决方案:

相关问题