生产中的静态文件出现 Django 301 和 403 禁止错误

问题描述 投票:0回答:6

我正在尝试使用nginx和gunicorn在ubuntu 14.04 vps上部署django网站,但是我的css文件和js文件没有加载。我在默认的django开发服务器上开发了它,它运行得很好,但是当我部署时我的网站和

collectstatic
并尝试通过浏览器访问它,仅加载 HTML 文本,在检查浏览器控制台时,我发现我的静态文件夹上有
301
403
forbidden
错误。我也是 ubuntu 和 django 的新手,我在网上找到的所有线程和论坛都只是指向文件的权限和所有权,并且当我更正我的权限时没有任何运气。

当我尝试访问 django admin 时浏览器错误的屏幕截图

这是我的设置.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__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/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 = ['mysite.com','www.mysite.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'powerlineapp',
]

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 = 'powerlineproject.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 = 'powerlineproject.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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.11/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.11/howto/static-files/


STATIC_URL = '/static/'

if not DEBUG: 
    STATIC_ROOT = '/var/www/powerline/powerlineproject/static/'


MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

这是我的主要 urls.py

from django.conf.urls import include,url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include('powerlineapp.urls')),

]

nginx.conf

user www-data www-data;
pid /var/run/nginx.pid;
worker_processes 1;
worker_rlimit_nofile 100000;

events {
    worker_connections  4096;
    include /etc/nginx.custom.events.d/*.conf;
}

http {
    default_type application/octet-stream;

    access_log off;
    error_log  /var/log/nginx/error.log crit;

    sendfile on;
    tcp_nopush on;

    keepalive_timeout 20;
    client_header_timeout 20;
    client_body_timeout 20;
    reset_timedout_connection on;
    send_timeout 20;

    types_hash_max_size 2048;

    gzip on;
    gzip_disable "msie6";
    gzip_proxied any;
    gzip_min_length 256;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;

    server_names_hash_bucket_size 128;

    include mime.conf;
    charset UTF-8;

    open_file_cache max=100000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    server_tokens off;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    include proxy.conf;
    include fcgi.conf;

    include conf.d/*.conf;
    include /etc/nginx.custom.d/*.conf;
}

include /etc/nginx.custom.global.d/*.conf;

我的站点配置文件

server {
    listen *:80;



    server_name powerlineagencies.co.ke;

    access_log /var/log/nginx/powerline-agencies.access.log;
    error_log /var/log/nginx/powerline-agencies.error.log;

    root /var/www/powerline/powerlineproject;
    index index.html index.htm index.php;





    location  / {



        proxy_pass http://unix:/var/run/ajenti-v-gunicorn-powerline-agencies-python-wsgi-0.sock;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    }


    location ~ /static/.* {
        alias /var/www/powerline/powerlineproject;




    }

}

这是我的目录结构

我的目录结构截图

有人可以帮我解决这个问题吗?

python django nginx ubuntu-14.04 gunicorn
6个回答
28
投票

Nginx 需要能够读取静态文件夹。您可以通过将 www-data 用户添加到您的项目用户所在的组来完成此操作。

sudo usermod -a -G your_user www-data

然后重启nginx。


7
投票

我通过将用户名(我在产品服务器中使用的)放入

nginx.conf
文件中解决了我的问题。

nginx.conf
文件可以在此位置找到:
/etc/nginx/nginx.conf

当我收到

403 Forbidden
错误时,用户部分是:
user www-data;
。我必须将其更改为
user ubuntu;
(因为我使用 ubuntu 用户来运行我的应用程序)。


1
投票
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在 ngix

location /static/ {    

            alias /var/www/powerline/powerlineproject/static/;    
         }  

将此行添加到 urls.py 和collectstatic,然后检查


0
投票

检查您的项目所有权:

ls -l <YOUR_PROJECT_FOLDER>
并确保您的用户和组与
nginx.conf
中的用户相同。

就您而言,您有

user www-data www-data;


0
投票

检查用户和组权限,可能有些javascript没有执行权限。 我的意思是静态文件夹和子文件夹的 rwx 权限。


0
投票

您只需在 Nginx 配置中添加 rootubuntu 用户即可允许默认用户访问静态文件。

Run the command: *sudo nano  /etc/nginx/nginx.conf*
At the top replace *user www-data* with *user root;* OR *user ubuntu;*
© www.soinside.com 2019 - 2024. All rights reserved.