mahbubcseju
mahbubcseju

Reputation: 2290

Django fails to serve static file in ec2?

I was trying to deploy a a django project on ec2 instance using nginx and uwsgi. The project works fine in development mode on local pc and can serve static files in localhost easily. But problem is after deploying on ec2 instance it can not load static files(css) files.

My project structure:

enter image description here

Settings files are inside setting directory:

Some part of Settings contents:

BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",                                                                                              "django.contrib.staticfiles",
    "control",
] 
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = (
      os.path.join(BASE_DIR, "static"),
)

nginx contents:

upstream url_shortener {
    server 127.0.0.1:8000;
}


server {
        listen 80;
    server_name mahbubcseju.com ;
    charset     utf-8;
    location = /favicon.ico {access_log off; log_not_found off; }

    location = /static/ {
        autoindex on;
        alias  /home/ubuntu/projects/url_shortener/static/;
    }

    location / {
        include        /etc/nginx/uwsgi_params;
        uwsgi_pass     url_shortener;
    }
}

uwsgi contents:

[uwsgi]
project = url_shortener
uid = ubuntu
base = /home/%(uid)

home = %(base)/projects
chdir = %(home)/%(project)
module = %(project).wsgi:application

master = true
processes = 5

chown-socket = %(uid):www-data
chmod-socket = 666
socket  = 127.0.0.1:8000
vacuum = true

plugins = python3,http

I ran python manage.py runserver collectstatic before starting nginx server.

If I try to access a css file from browser, it provied the following error:

Request:
http://mahbubcseju.com/static/css/home.css
Response:

Not Found The requested resource was not found on this server.

Static directory permision for user ubuntu:

drwxrwxrwx 4 ubuntu ubuntu 4096 Nov 7 07:50 static

Upvotes: 0

Views: 755

Answers (1)

2ps
2ps

Reputation: 15926

Take off the = from your location block in the nginx config, and this should work assuming the correct permissions have been set up on the directories to allow the nginx user access:

    location /static/ {
        # autoindex on;
        alias  /home/ubuntu/projects/url_shortener/static/;
    }

Upvotes: 1

Related Questions