所有静态资源未加载- Django,Gunicorn,NGINX

30byixjq  于 2023-06-21  发布在  Nginx
关注(0)|答案(1)|浏览(122)

我运行Ubuntu 22.04,gunicorn,Django和Nginx。每次加载主页时:http://dev.api.afisado.com,没有加载任何CSS并执行js。在Chrome的开发者标签页中,我看到一个404未找到。我不知道该怎么办。
文件夹结构如下:

/home/devbackend_directory/core/static/

下面是我的www.example.com的settings.py样子:

STATIC_URL = '/static/'
STATIC_ROOT = '/home/devbackend_directory/core/static/'
MEDIA_ROOT = '/home/devbackend_directory'
MEDIA_URL = '/media/'

nginx文件:

server
 listen 80;
        server_name dev.api.afisado.com;

        location = /favicon.ico { access_log off; log_not_found off;}

        location static/ {

                root /home/devbackend_directory/core/static/;
        }

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

这是我的Gunicorn服务文件:

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=ali
Group=www-data
WorkingDirectory=/home/devbackend_directory/core/
ExecStart=/usr/bin/gunicorn \
         --access-logfile - \
         --workers 3 \
         --bind unix:/run/gunicorn.sock \
         core.wsgi:application

[Install]
WantedBy=multi-user.target
eanckbw9

eanckbw91#

确保你运行了collectstatic,当DEBUG设置为False时,Django不会在应用程序中查找静态目录,它必须在指定的位置。如果仍然不起作用,请尝试以下设置,这是我通常在托管www.example.com时所做的urls.py

from django.urls import re_path as url
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve

urlpatterns = [
    url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
    url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}),

] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

if DEBUG:
    STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

相关问题