django nginx static files 404

2020-08-09 08:48发布

Here are my settings :

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

STATIC_ROOT = '/home/django-projects/tshirtnation/staticfiles'

Here's my nginx configuration:

server {
    server_name 77.241.197.95;

    access_log off;

    location /static/ {
        alias /home/django-projects/tshirtnation/staticfiles/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
}

I've run python manage.py collectstatic and it has copied all static files. I run my server with gunicorn_django --bind:my-ip:8001 and everything seems to be working except for static files.

EDIT: I've run

sudo tail /var/log/nginx/error.log

and there seems to be no errors of static files not found :/

11条回答
家丑人穷心不美
2楼-- · 2020-08-09 09:14

Try to remove slash in nginx settings followed by static e.g. It should be "/static" not "/static/", and if your settings were fine then try to reload the server on local machine and try rebooting on remote machine. I faced similar but after rebooting the machine, fixed the issue.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-08-09 09:16

Try adding the ^~ prefix modifier to your static location to skip checking regular expressions:

location ^~ /static/ {
    alias /home/django-projects/tshirtnation/staticfiles/;
}
查看更多
走好不送
4楼-- · 2020-08-09 09:18

try this in settings.py:

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

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(ROOT_PATH,'static/')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]

and config file in nginx(or your server setting):

location /static {
    alias /home/djangohome/static; # your Django project's static files - amend as required
}
查看更多
走好不送
5楼-- · 2020-08-09 09:25

Use STATIC_URL with domain. It's important!

查看更多
Viruses.
6楼-- · 2020-08-09 09:29

I encountered the same problem and was able to fix my nginx configuration by removing the trailing / from the /static/ location.

location /static {  # "/static" NOT "/static/"
    # ...
}
查看更多
登录 后发表回答