You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Django管理后台静态文件(CSS/JS)缺失404问题求助

Fixing Django Admin Static Files 404 with Nginx + Gunicorn

Hey there! Let's work through this static file issue step by step—this is a super common hiccup when setting up Django with Nginx, so you're not alone. Here are the key things to check and fix:

1. Verify Your STATIC_ROOT Path Matches Nginx's Configuration

First, let's make sure Django is collecting static files to the exact directory Nginx is pointing to.

  • Open a Django shell with python manage.py shell, then run these commands:
    import os
    print(BASE_DIR)
    print(os.path.join(BASE_DIR, "static"))
    
  • Compare the output of os.path.join(BASE_DIR, "static") to the alias path in your Nginx config (/opt/myenv/myenv/MYPROJECT/static/). If they don't match, that's a core problem—collectstatic is putting files in one place, but Nginx is looking somewhere else.

2. Ensure collectstatic Is Working Correctly

You mentioned running collectstatic, but let's double-check where it's placing the admin files:

  • Re-run the command with verbose output to see exactly where files are going:
    python manage.py collectstatic --verbosity 2
    
  • After running this, confirm the admin static files exist in /opt/myenv/myenv/MYPROJECT/static/admin/ (you don't need the separate /opt/myenv/myenv/static/admin/ directory—Nginx is only configured to serve from the project's static folder).

3. Fix Nginx Configuration & Permissions

Your current Nginx config is close, but let's add critical details to avoid permission issues and ensure proper serving:

  • Update your location /static block like this:
    location /static {
        alias /opt/myenv/myenv/MYPROJECT/static/;
        # Cache static files for better performance
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
        # Ensure Nginx can read the files
        autoindex off;
        allow all;
    }
    
  • Next, fix directory permissions so the Nginx user (usually www-data) can access the static files:
    sudo chown -R www-data:www-data /opt/myenv/myenv/MYPROJECT/static/
    sudo chmod -R 755 /opt/myenv/myenv/MYPROJECT/static/
    

4. Restart Services to Apply Changes

After updating configs and permissions, you need to restart Nginx and Gunicorn for changes to take effect:

sudo systemctl restart nginx
sudo systemctl restart gunicorn # Adjust this if you manage Gunicorn with a different method

5. Debug with Nginx Logs

If you still see 404s, check Nginx's error log to get the exact cause:

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

Try accessing a static file directly (like http://MYPROJECT.COM/static/admin/css/base.css) while watching the log—it will tell you if Nginx can't find the file (wrong path) or can't read it (permission issue).


内容的提问来源于stack exchange,提问作者J. Santiago

火山引擎 最新活动