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

Django+Gunicorn+Nginx环境下静态资源无法加载问题求助

Django+Gunicorn+Nginx部署静态资源404问题修复

问题描述

Ubuntu 22.04系统上部署Django、Gunicorn和Nginx后,访问http://dev.api.afisado.com主页时CSS完全无法加载,JS执行异常,Chrome开发者工具显示静态资源404错误。

当前配置信息

目录结构

/home/devbackend_directory/core/static/

Django 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

问题原因分析

  1. Nginx静态资源路径配置错误:原location static/缺少开头的/,匹配规则无效;且root参数指向静态资源目录本身,导致Nginx在错误路径下查找资源。
  2. 未确认是否执行collectstatic命令,静态资源可能未被收集到STATIC_ROOT目录。
  3. 静态资源目录权限不足,Nginx运行用户无法读取资源。

修复步骤

1. 修正Nginx静态资源配置

将Nginx配置中的静态资源location块修改为以下两种方式之一:

方式一:使用root(推荐)

location /static/ {
    root /home/devbackend_directory/core/;
    expires 30d;
    add_header Cache-Control "public, max-age=2592000";
}

解释:root指定静态资源目录的上级目录,当请求/static/css/style.css时,Nginx会从/home/devbackend_directory/core/static/css/style.css读取资源,匹配你的STATIC_ROOT路径。

方式二:使用alias

location /static/ {
    alias /home/devbackend_directory/core/static/;
    expires 30d;
    add_header Cache-Control "public, max-age=2592000";
}

解释:alias直接将/static/路径映射到指定静态资源目录,请求路径中的/static/会被替换为alias后的路径。

2. 执行Django collectstatic命令

确保所有App的静态资源被收集到STATIC_ROOT目录:

cd /home/devbackend_directory/core/
python manage.py collectstatic

执行时输入yes确认覆盖(如有提示)。

3. 修复静态资源目录权限

确保Nginx运行用户(www-data)拥有静态资源的读取权限:

sudo chown -R ali:www-data /home/devbackend_directory/core/static/
sudo chmod -R 755 /home/devbackend_directory/core/static/

4. 重启Nginx服务

使配置生效:

sudo systemctl restart nginx

内容的提问来源于stack exchange,提问作者Ali-CCIE63081

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:17:31