Ubuntu Server部署Django+Gunicorn+Nginx静态资源加载失败求助
Ubuntu Server部署Django+Gunicorn+Nginx后静态资源无法加载问题排查
错误日志
Nginx错误日志
/var/log/nginx/error.log内容:
[error] 714#714: *5 open() "/home/<user>/<projects>/static/css/custom.css" failed (13: Permission denied), client: ip, server: domain, request: "GET /static/css/custom.css HTTP/1.1", host: "domain", referrer: "http://domain/"
相关配置文件
Nginx站点配置(/etc/nginx/sites-available/<project>)
server { listen 80; server_name <domain>; location = /favicon.ico { access_log off; log_not_found off; } location /collected_static/ { root /home/<user>/<project>; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } }
Gunicorn服务配置(/etc/systemd/system/gunicorn.service)
[Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=vsevolod Group=www-data WorkingDirectory=/home/<user>/<project> ExecStart=/home/<user>/<project>/myvenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ config.wsgi:application [Install] WantedBy=multi-user.target
Django settings.py配置
STATIC_URL = '/static/' STATICFILES_DIRS = ( BASE_DIR / 'static', ) STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')
用户操作与疑问
- 疑问:是否Nginx配置文件中必须指定
python3 manage.py collectstatic生成的目录,才能让Nginx正确加载静态资源? - 操作:
- 执行
sudo -u www-data stat /home/<user>/<project>/collected_static提示权限不足 - 执行
sudo gpasswd -a www-data <user>,重启Nginx和服务器,但静态资源仍无法加载,日志报错依旧
- 执行
- 背景:项目两年前部署正常,现在按指南操作却出问题,不熟悉运维,请求帮助
- 更新:将
/home/<user>/<project>/collected_static下所有目录权限设为750后,日志无错误,但静态资源仍无法加载
解决方案
1. 修正Nginx静态资源路由匹配
你的Nginx配置里,location /collected_static/对应的是URL路径为/collected_static/xxx的请求,但前端页面实际请求的是/static/xxx,两者不匹配,这是核心问题。需要把Nginx的静态资源location改成对应STATIC_URL的路径:
正确的配置应该是:
location /static/ { alias /home/<user>/<project>/collected_static/; }
说明:alias会直接把URL中/static/开头的部分替换成指定的collected_static目录路径,这样/static/css/custom.css就会指向/home/<user>/<project>/collected_static/css/custom.css,和collectstatic生成的文件路径对应。
2. 确保完整目录权限链可访问
虽然你已经设置了collected_static的权限,但上级目录的权限也会影响www-data的访问,执行以下命令修复:
# 确保用户目录允许组访问 sudo chmod 750 /home/<user>/ # 确保项目目录允许组访问 sudo chmod 750 /home/<user>/<project>/ # 给collected_static设置正确的属主和权限 sudo chown -R <user>:www-data /home/<user>/<project>/collected_static/ sudo chmod -R 750 /home/<user>/<project>/collected_static/
3. 重新执行collectstatic确保文件完整
重新收集静态文件,确保所有资源都被同步到collected_static目录:
cd /home/<user>/<project>/ source myvenv/bin/activate python manage.py collectstatic --noinput
执行后检查collected_static/css/下是否存在custom.css文件。
4. 重启服务生效
修改配置后,重启Nginx和Gunicorn:
sudo systemctl restart nginx sudo systemctl restart gunicorn.service
内容的提问来源于stack exchange,提问作者Владимир Рост
相关产品推荐
相关产品推荐

