【问题标题】:How to serve static file via nginx?如何通过 nginx 提供静态文件?
【发布时间】:2015-03-18 06:54:31
【问题描述】:

静态文件不能通过 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

【问题讨论】:

标签: django nginx


【解决方案1】:

首先你检查你的静态文件的设置应该看起来像这个设置

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 # 这将收集所有静态 文件到collected_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 权限问题,您可以从以下链接找到解决方案:

【讨论】:

猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 2011-01-16
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多