Django、Nginx、Gunicorn 静态文件不工作

标签 django nginx centos gunicorn

我正尝试在 CentOS 服务器上建立一个网站。我的堆栈由 Django、PostgreSQL 和 Nginx/Gunicorn 组成。 我的 Nginx 版本是 1.7.7。我在配置服务器时遇到问题,因此我的 Django 应用程序无法访问我的静态文件 (css/js)。

配置如下:

/var/www/domain.com/

/var/www/domain.com
    ├── Repository/
    │   ├── wsgi.py
    │   ├── manage.py
    │   ├── static
    │   │    ├── css/
    │   │    └── js/
    │   ├── apps/
    │   └── more apps...
    ├── error/
    │   └── 404.html
    ├── public/
    │   ├── 400.html
    │   ├── 404.html
    │   └── 500.html

/etc/nginx/conf.d/django.conf

upstream django_project {
  server 127.0.0.1:8003 fail_timeout=0;
}

最后,在 /etc/nginx/sites/01-domain.com.conf

server {
    #listen   80; ## listen for ipv4; this line is default and implied
    #listen   [::]:80 default_server ipv6only=on; ## listen for ipv6

    #root /var/www/domain.com;
    index index.html index.htm;

    # Make site accessible from http://localhost/
    server_name domain.com;

    root /var/www/domain.com/public;

    #location / {
    #       # First attempt to serve request as file, then
    #       # as directory, then fall back to displaying a 404.
    #       #try_files $uri $uri/ /index.html;
    #       # Uncomment to enable naxsi on this location
    #       # include /etc/nginx/naxsi.rules
    #}

    location /static/ { # STATIC_URL
            #root /var/www/firewall/static/;
            root /var/www/domain.com/Repository/static/; # STATIC_ROOT
            expires 30d;
    }

    location ^~ /media/ { # MEDIA_URL
            root /var/www/domain.com/Repository; # MEDIA_ROOT
    }

    location ^~ /admin/media/js/admin/ {
            root /opt/python-3.4.2/lib/python3.4/site-packages/Django-1.7.1-py3.4.egg/django/contrib/admin/static;
    }

    #location ^~ /admin/media/image {
    #        root /opt/python-2.7.8/lib/python2.7/site-packages/django/contrib/admin/static/admin/image/;
    #}

    #location ^~ /admin/media/css {
    #        root /opt/python-2.7.8/lib/python2.7/site-packages/django/contrib/admin/static/admin/css/;
    #}


    location /static/admin { # MEDIA_URL
            root /opt/python-3.4.2/lib/python3.4/site-packages/Django-1.7.1-py3.4.egg/django/contrib/admin;
    }

    #location /admin/img { # MEDIA_URL
    #        root /opt/python-2.7.8/lib/python2.7/site-packages/django/contrib/admin/static; # MEDIA_ROOT
    #}

    #location /admin/js { # MEDIA_URL
    #        root /opt/python-2.7.8/lib/python2.7/site-packages/django/contrib/admin/static; # MEDIA_ROOT
    #}


    location / {
            try_files $uri @app_proxy;

    }


    location @app_proxy {
        proxy_set_header   Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_redirect off;

        proxy_pass   http://django_project;
    }

    error_page 400 401 402 403 404 /400.html;
    #location = /400.html {
    #    root /var/www/domain.com/error;
    #}

    error_page 500 502 503 504 /500.html;
    #location = /500.html {
    #    root /var/www/domain.com/error;
    #}

    #location / {
    #        include fastcgi_params;
    #        #fastcgi_pass 127.0.0.1:8080;
    #        proxy_pass http://127.0.0.1:8003;
    #}

}

上面的文件是我从我看到的一个例子中复制过来的。我很确定我需要帮助的两个部分是以 location/staticlocation ^~/media/ 开头的行。我认为这些是为我的实际代码服务的,所以如果我的服务器配置有问题或我的文件位于错误的位置,有人可以告诉我应该如何处理吗?

此外,这是我的Repository/homeapp/settings.py

"""
Django settings for homeapp project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

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


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

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

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

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'homeapp',
    'crispy_forms',
    'app1',
    'app2',
    'app3',
    'app4',
    'app5',
    'app6',
    'app7',
    'app8',
    'app9',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'homeapp.urls'

WSGI_APPLICATION = 'homeapp.wsgi.application'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'homeapp/templates'),
    os.path.join(BASE_DIR, 'app1/templates'),
    os.path.join(BASE_DIR, 'app2/templates'),
    os.path.join(BASE_DIR, 'app3/templates'),
    os.path.join(BASE_DIR, 'app4/templates'),
    os.path.join(BASE_DIR, 'app5/templates'),
    os.path.join(BASE_DIR, 'app6/templates'),
    os.path.join(BASE_DIR, 'app7/templates'),
    os.path.join(BASE_DIR, 'app8/templates'),
    os.path.join(BASE_DIR, 'app9/templates'),
)


# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name',
        'USER': 'user',
        'PASSWORD': 'passwd',
        'HOST': 'localhost',
        'POST': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/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.7/howto/static-files/

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

CRISPY_TEMPLATE_PACK = 'bootstrap3'

最佳答案

尝试删除 nginx 配置中的尾随目录名称:

root /var/www/domain.com/Repository/; # STATIC_ROOT

因为在你的情况下 nginx 将提供这样的文件:

/var/www/domain.com/Repository/static/static/...

检查您的 nginx 错误日志中是否有如下行:

open() "/var/www/domain.com/Repository/static/static/.../somefile" failed (2: No such file or directory),

关于Django、Nginx、Gunicorn 静态文件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245249/

相关文章:

django - 如何使用相同的 django 表单编辑/添加对象?

ruby-on-rails - 并发 Net::HTTP.get 到同一个域

python - 在 Centos 8 上安装 Python 3 返回 "Failed to synchronize cache for repo ' BaseOS'"

docker - 带有外部 nginx 和综合的 gitlab docker 注册表

nginx - 我使用 Homebrew 软件安装 nginx,如何添加第三个模块?

if-statement - 仅当 cookie 存在时,如何有条件地覆盖 nginx 中的 header ?

node.js - 如何在我的专用服务器上安装 Node Js

python - 如何使用相同的数据库后端运行在同一服务器上运行多个实例的 Django 1.6 项目?

python - Django上传csv文件复制到postgresql表

python - 如何在 Django 中使用过滤后的数据填充表