简体   繁体   中英

Static files only served when debug = True and does not when it is False in production for nginx ubuntu 22.04

I have followed the setup procedures here https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 and my Django app is running but whenever I turn debug = False it will not load my static files.

Below is my nginx configuration:

server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/myprojectdir;
    }

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

and my settings.py:

STATIC_URL = 'static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

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

I have tried my best, researched a lot online, and followed many links but still fruitless.

I think this is due to the fact that in your project url.py there is a line:

if settings.DEBUG:
    urlpatterns += static(....)

I also recommend that you replace root with alias :

location /static/ {
        alias /home/sammy/myprojectdir;
    }

and execute the statiс collection command:

python3 manage.py collectstatic

and lastly, make sure that you do not have the conditions for checking the debug mode anywhere

UPDATE : Make sure nginx looks for static where you have STATIC_ROOT :

location /static/ {
        alias /home/sammy/myprojectdir/static/;
    }

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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