nginx ??? not able to access Django's static files

1.1k Views Asked by At

hi i need help with the below:

my static image file does not load when I use nginx/supervisord to start my django app, however when I start using django manage.py the image loads no problem.

I have search many django/nginx static docs to no avail. My image shows when i run

python manage.py runserver 0.0.0.0:9000

but when I run with nginx/supervisor all pages load fine except the image from my static dir. I have confirmed i dont have a syntax issue with my nginx configs:

nginx -t -c /etc/nginx/nginx.conf
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx conf: (actually the below is from nginx-django.conf the nginx.conf is just the default config that comes with the install)

#HTTPS server configuration

upstream django_app {
    server 127.0.0.1:9000;
}


server {
    listen       8443 ssl;
    server_name  _;

    ssl                  on;
    ssl_certificate      /etc/nginx/ssl/cert.crt;
    ssl_certificate_key  /etc/nginx/ssl/cert.key;

    ssl_session_timeout  5m;

    ssl_protocols  SSLv2 SSLv3 TLSv1;
    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    ssl_prefer_server_ciphers   on;

    proxy_buffer_size   128k;
    proxy_buffers   4 256k;
    proxy_busy_buffers_size   256k;

        location / {

            proxy_pass         http://django_app;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $host;
            proxy_connect_timeout   1800;
            proxy_read_timeout   1800;
            proxy_send_timeout   1800;

        }

        location ^/static/ {

            alias /home/vagrant/gentools/static;
            expires  3d;

        }

}

My supervisord config is as follows and starts up without errors:

[unix_http_server]
file=/tmp/supervisor.sock   ; (the path to the socket file)

[supervisord]
logfile=/tmp/supervisord.log  ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;default 10)
loglevel=info               ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false              ; (start in foreground if true;default false)
minfds=1024                 ; (min. avail startup file descriptors;default 1024)
minprocs=200                ; (min. avail process descriptors;default 200)

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[program:gunicorn]
directory=/home/vagrant/gentools
command=/home/vagrant/venv/bin/gunicorn --workers 1 --bind 0.0.0.0:9000 gentools.wsgi:application
autostart=true
autorestart=true
stderr_logfile=/tmp/gunicorn.out.log
stdout_logfile=/tmp/gunicorn.err.log
user=vagrant
environment=PYTHONPATH=/home/vagrant/gentools/gentools,DJANGO_SETTINGS_MODULE=settings,LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL  for a unix socket

My folder structure is as follows:

├── gentools
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
├── manage.py
├── static
│   ├── admin
│   ├── css
│   ├── images
│   └── js
├── supervisor
│   ├── conf.d
│   └── supervisord.conf
└── templates
    ├── base.html
    ├── home.html
    ├── logged_out.html
    └── login.html

As I mentioned I can start the django app successfully using nginx/supervisor the only error i see in the logs is related to the file that is not loading:

Not Found: /static/images/my_logo.jpg

from settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),],
        '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',
            ],
        },
    },
]

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    '/home/vagrant/gentools/static/',
    os.path.join(BASE_DIR, "static"),
]

from urls.py:

from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', login_required(TemplateView.as_view(template_name='home.html')), name='home'),
    url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'),
]

lastly from my template base.html:

 {% load static %}

    <img src={% static "images/my_logo.jpg" %}>

thanks in advance!

2

There are 2 best solutions below

0
On BEST ANSWER

thanks for prompt reply qnnnnez. I got a good read thanks for the link but did not find out why that line causes issues. I tried all permutations of /static/, ^/static/ etc. I did some more googling and fiddling and this seems to have resolved my issue:

edit urls.py to include:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    ....
] + staticfiles_urlpatterns()

I also modified the location part of the nginx config, not sure if this helped any I dont have time to go back and check:

nginx config:

location /static/ {

    autoindex on;
    alias /home/vagrant/gentools/static/;
    expires  3d;

}

I no longer get errors from gunicorn. Now I get nginx permissions which I am off to solve now and is out of scope of this question.

Hope the above helps someone.

0
On

The location ^/static { part of your nginx.conf courses the problem.

See nginx docs for detail: http://nginx.org/en/docs/http/ngx_http_core_module.html#location

Also, you may want to use uWSGI instead.