You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行collectstatic后Django项目CSS无法加载问题求助

Django静态文件无法加载的排查与修复

核心问题分析

你的Nginx配置存在关键错误:80端口的server块里配置了静态文件规则,但该块直接执行return 301跳转至HTTPS,导致静态文件的location规则从未生效。所有HTTP请求会被强制跳转到HTTPS,但HTTPS的server块中没有处理静态文件的配置,因此静态文件请求会被转发到Django后端,而Django在生产环境(DEBUG=False)下不会处理静态文件请求,最终导致CSS等静态资源无法加载。

分步修复方案

1. 修正Nginx配置

将静态文件和媒体文件的location规则移至HTTPS的server块内,删除80端口server块中无效的配置:

server {
    listen 80;
    server_name my-wow-site.com www.my-wow-site.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name my-wow-site.com www.my-wow-site.com;

    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # 静态文件处理规则
    location /static/ {
        alias /root/wow_site/staticfiles/;
        # 可选:添加缓存优化
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }

    # 媒体文件处理规则
    location /media/ {
        alias /root/wow_site/media/;
    }

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

2. 检查文件权限

Nginx进程默认以www-data用户运行,而/root目录的默认权限是700,www-data用户无法访问该目录下的文件。解决方式二选一:

  • 推荐:将项目目录从/root/wow_site移动到非root用户目录,比如/var/www/wow_site或/home/your-user/wow_site,然后调整目录权限:
    sudo chown -R www-data:www-data /var/www/wow_site/staticfiles
    sudo chmod -R 755 /var/www/wow_site/staticfiles
    
  • 若必须保留在/root目录,临时放宽权限(不推荐,存在安全风险):
    sudo chmod 755 /root
    sudo chown -R www-data:www-data /root/wow_site/staticfiles
    sudo chmod -R 755 /root/wow_site/staticfiles
    

3. 验证静态文件收集

重新执行collectstatic命令,确认静态文件已正确收集到staticfiles目录:

python3 manage.py collectstatic --noinput

执行完成后,检查/root/wow_site/staticfiles目录下是否包含CSS、JS等静态资源文件。

4. 重启Nginx服务

确保配置生效:

sudo nginx -t  # 先验证配置语法是否正确
sudo systemctl restart nginx

5. 确认生产环境配置

确保settings.py中DEBUG=False(生产环境必须关闭DEBUG,否则存在安全风险),且STATIC_ROOT和STATIC_URL配置正确:

DEBUG = False
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'  # 建议添加开头的斜杠,避免路径拼接问题

内容的提问来源于stack exchange,提问作者mdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 20:03:24