[Answer]-Django app + nginx fail to server static files

1๐Ÿ‘

OK, the problem is that Django's static files are served by default from www.myapp.com/static/ folder so there is no reason specifying the /static/ folder in the nginx configuration file. So if anyone else has the same problem, just remove the following part from nginx/sites-enabled/myapp file:

location /static/ { # STATIC_URL
        alias /home/apps/myapp/static/; # STATIC_ROOT
            expires 30d;
        }
        location /media/ { # MEDIA_URL
            alias /home/apps/myapp/media/; # MEDIA_ROOT
            expires 30d;
        }
๐Ÿ‘คAndrei Stalbe

0๐Ÿ‘

Have you ran python manage.py collectstatic on your server?

Make sure the file is in the static root directory.

๐Ÿ‘คBigcortex

0๐Ÿ‘

1 โ€“ Make sure your main urls.py contains static & media routes, it should look like this:

$ nano /home/myuser/apps/myapp/urls.py
----
urlpatterns = [
    path('admin/', admin.site.urls),
    # here goes your other routes ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

2 โ€“ Make sure STATIC_ROOT, STATIC_URL, MEDIA_ROOT, MEDIA_URL are defined in your settings.py :

$ nano `/home/myuser/apps/myapp/settings.py`
----
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = 'static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'

3 โ€“ Make sure your static and media paths are correct for Nginx:

`$ sudo nano /etc/nginx/sites-available/myapp`
----
# STATIC_URL
location /static/ { 
    alias /home/myuser/apps/myapp/static/;
    expires 30d;
}

# MEDIA_URL
location /media/ { 
    alias /home/myuser/apps/myapp/media/; # MEDIA_ROOT
    expires 30d;
}

4 โ€“ Make sure your statics were generated properly:

python3 manage.py collectstatic

5 โ€“ Make sure your static and media are accessible for Nginx:

$ cd myproject
$ sudo chown -R www-data:www-data /home/myuser/apps/myapp/media/
$ sudo chown -R www-data:www-data /home/myuser/apps/myapp/static/
$ sudo chmod -R 755 /home/myuser/apps/myapp/media/
$ sudo chmod -R 755 /home/myuser/apps/myapp/static/

6 โ€“ Restart Nginx:

$ sudo systemctl restart nginx

Good Luck !

Leave a comment