简体   繁体   English

使用 gunicorn nginx 在 aws 上部署 django 应用程序后,css 无法正常工作

[英]css is not working after deploying django application on aws with gunicorn nginx

I have deployed my django project on EC2 but the css is not working after deployement.我已经在 EC2 上部署了我的 django 项目,但部署后 css 无法正常工作。 I also ran collcectstatic command but still got unlucky, when I checked in nginx error.log it showing in front of css files that permission denied like this:我还运行了 colcectstatic 命令,但仍然不走运,当我签入 nginx error.log 时,它在 css 文件前面显示权限被拒绝,如下所示:

2022/07/18 17:38:01 [error] 2262#2262: *4 open() "/home/ubuntu/theoj/online_judge_project/staticindex.css" failed (13: Permission denied), client: 49.38.225.106, server: 13.126.144.76, request: "GET /static/index.css HTTP/1.1", host: "13.126.144.76", 2022/07/18 17:38:01 [错误] 2262#2262: *4 open() "/home/ubuntu/theoj/online_judge_project/staticindex.css" 失败(13:权限被拒绝),客户端:49.38.225.106,服务器:13.126.144.76,请求:“GET /static/index.css HTTP/1.1”,主机:“13.126.144.76”,

my project directory structure:我的项目目录结构:

online_judge_project/
                    account/
                    homesrc/
                    language/
                    media/
                    oj/ /*name of my project*/
                      settings.py
                    problempg/
                    static/ /* folder containing css files*/
                    staticfiles/ /* folder made after running command collectstatics*/
                    template/
                    manage.py

**settings.py: ** **设置.py:**

"""
Django settings for oj project.

Generated by 'django-admin startproject' using Django 4.0.5.

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

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

from importlib.resources import path
from pathlib import Path
import os
from .info import *

EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
EMAIL_PORT = EMAIL_PORT
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'template')
FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language'))

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

# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = "django-insecure-14$m%70aq1-xqy9z2jt9nva)f_&y5xba3j3g40!3oaqvvyu8_p"

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

ALLOWED_HOSTS = ["my_IP_address","localhost"]


# Application definition

INSTALLED_APPS = [
    'widget_tweaks',
    'account.apps.AccountConfig',
    'problempg.apps.ProblempgConfig',
    'homescr.apps.HomescrConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ckeditor',
]

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 = 'oj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        '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 = 'oj.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/4.0/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/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT= os.path.join(BASE_DIR,'staticfiles')
STATIC_URL = 'static/'
MEDIA_ROOT= os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
LOGOUT_REDIRECT_URL = "index"

STATICFILES_DIRS=[
    os.path.join(BASE_DIR, 'static'),
]

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

from django.contrib.messages import constants as messages

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

nginx congif file: nginx 配置文件:

server {
    listen 80;
    server_name 13.126.144.76;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/ubuntu/theoj/online_judge_project;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

To get the static files to load correctly for me, I had to put them into a directory in the /var/ folder and then add location /static { autoindex on; root /var/WebApp_Static_Files/site_static; }为了让静态文件为我正确加载,我必须将它们放入 /var/ 文件夹中的目录中,然后添加location /static { autoindex on; root /var/WebApp_Static_Files/site_static; } location /static { autoindex on; root /var/WebApp_Static_Files/site_static; } location /static { autoindex on; root /var/WebApp_Static_Files/site_static; } to the nginx config for the site. location /static { autoindex on; root /var/WebApp_Static_Files/site_static; }到该站点的 nginx 配置。 Make sure the /var/WebApp_Static_Files directory has 777 permissions确保 /var/WebApp_Static_Files 目录有 777 权限

To clarify, this is a copy of all static files in this directory that lives on the server running Nginx, the project structure doesn't need to change澄清一下,这是该目录中所有静态文件的副本,位于运行 Nginx 的服务器上,项目结构不需要更改

You will need to push the files to the server every time you make a change to the css, images, and everything.每次更改 CSS、图像和所有内容时,都需要将文件推送到服务器。 I set up a cron job to do this periodically so that I didn't need to do it manually我设置了一个 cron 作业来定期执行此操作,因此我不需要手动执行此操作

Also, you may want to remove your secret key from the above code此外,您可能希望从上述代码中删除您的密钥

In the absence of STATICFILES_STORAGE, your location value in your nginx config should reflect the name of the folder you are putting your files in. In this case, the same folder as your STATIC_ROOT.在没有 STATICFILES_STORAGE 的情况下,您在 nginx 配置中的位置值应该反映您放置文件的文件夹的名称。在这种情况下,与您的 STATIC_ROOT 相同的文件夹。

location /static/ {
    alias /home/ubuntu/theoj/online_judge_project/staticfiles/;
}

(Using alias not root as the final directories have different names) (使用alias而不是root ,因为最终目录具有不同的名称)

Ideally, STATIC_ROOT is a holding pen before deployment elsewhere (eg STATICFILES_STORAGE), but this should get your site working for now.理想情况下,STATIC_ROOT 是在其他地方部署之前的一个保持笔(例如 STATICFILES_STORAGE),但这应该让您的站点现在可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM