skip to Main Content

I have deployed my django project on EC2 but the css is not working after deployement. 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:

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",

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: **

"""
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:

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;
    }
}

2

Answers


  1. 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; } to the nginx config for the site. Make sure the /var/WebApp_Static_Files directory has 777 permissions

    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

    You will need to push the files to the server every time you make a change to the css, images, and everything. I set up a cron job to do this periodically so that I didn’t need to do it manually

    Also, you may want to remove your secret key from the above code

    Login or Signup to reply.
  2. 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.

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

    (Using alias not root as the final directories have different names)

    Ideally, STATIC_ROOT is a holding pen before deployment elsewhere (eg STATICFILES_STORAGE), but this should get your site working for now.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search