没有使用Django / Nginx的图像

时间:2016-12-10 18:03:09

标签: python django nginx gunicorn

我似乎无法弄清楚为什么在我的其他静态文件出现时我的图像没有被提供。

我跟随这个tutorial,一切正常,除了图像没有被提供。但是,提供了所有其他静态文件(css,js等)。

我已经尝试查看Django Docs,几个SO帖子和Nginx文档。

阅读上述内容后,我尝试将静态文件移动到不同的位置,包括STATICFILES_DIR。看起来静态文件正在被Nginx找到并提供服务(img目录除外)。当我使用Chrome开发者工具检查来源时,我可以看到css和js文件,而不是img目录和文件。

我非常感谢你们所有人的帮助!

Settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))

# TEMPLATE_DIRS = (
#     os.path.join(SETTINGS_PATH, 'templates'),
# )


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '**'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['138.197.19.209']


# Application definition

INSTALLED_APPS = [
    'material',
    'material.frontend',
    'material.admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ihc',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ihc_data.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ihc_data.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '../static/')

Nginx网站可用

upstream app_server {
    server unix:/home/urban/run/gunicorn.sock fail_timeout=0;
}

server {
    listen 80;

    # add here the ip address of your server
    # or a domain pointing to that ip (like example.com or www.example.com)
    server_name 138.197.19.209;

    keepalive_timeout 5;
    client_max_body_size 4G;

    access_log /home/urban/logs/nginx-access.log;
    error_log /home/urban/logs/nginx-error.log;

    location /static/ {
        alias /home/urban/static/;
    }

    # checks for static file, if not found proxy to app
    location / {
        try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://app_server;
    }
}

Nginx错误日志(示例)

2016/12/10 17:41:52 [error] 12773#12773: *52 open() "/home/urban/static/img/projects.png" failed (2: No such file or directory), client: 24.11.95.201, server: 138.197.19.209, request: "GET /static/img/projects.png HTTP/1.1", host: "138.197.19.209", referrer: "http://138.197.19.209/vizes/Projects"
2016/12/10 17:41:55 [error] 12773#12773: *54 open() "/home/urban/static/img/savings.png" failed (2: No such file or directory), client: 24.11.95.201, server: 138.197.19.209, request: "GET /static/img/savings.png HTTP/1.1", host: "138.197.19.209", referrer: "http://138.197.19.209/vizes/Projects"
2016/12/10 17:41:55 [error] 12773#12773: *52 open() "/home/urban/static/img/projects.png" failed (2: No such file or directory), client: 24.11.95.201, server: 138.197.19.209, request: "GET /static/img/projects.png HTTP/1.1", host: "138.197.19.209", referrer: "http://138.197.19.209/vizes/Projects"
2016/12/10 17:41:55 [error] 12773#12773: *55 open() "/home/urban/static/img/project_savings.png" failed (2: No such file or directory), client: 24.11.95.201, server: 138.197.19.209, request: "GET /static/img/project_savings.png HTTP/1.1", host: "138.197.19.209", referrer: "http://138.197.19.209/vizes/Projects"

Chrome开发者工具控制台(以防万一)

loadScript @ tableau-2.js:28(anonymous function) @ tableau-2.js:32(anonymous function) @ tableau-2.js:33
Projects:94 GET http://138.197.19.209/static/img/projects.png 404 (Not Found)

1 个答案:

答案 0 :(得分:1)

我使用的一般清单是:

  1. 确保文件存在于目录中:

    ls -lah /home/urban/static/img/projects.png
    
  2. 确保nginx用户可以读取该目录中的文件:

    # Note we are making these files world-readable here 
    # alternatives are to use a common gunicorn/nginx user
    # or to use a group for both the nginx & gunicorn users.
    chmod 0755 /home/urban
    find /home/urban/static -type d -exec chmod a+rx {} \; 
    find /home/urban/static -type f -exec chmod a+r {} \;
    
  3. 如果(1)中不存在这些文件,请确保已运行collectstatic管理命令。它会复制static中的所有INSTALLED_APPS子目录,并将其复制到STATIC_ROOT