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

Django+Nginx+Gunicorn部署下媒体文件无法加载求助

Django部署Nginx+Gunicorn媒体文件无法加载的解决办法
  • 修正settings.py的拼写错误
    你把MEDIA_URL拼写成了MEIDA_URL,这会导致Django生成的媒体资源URL不正确,直接修改:

    MEDIA_URL = '/media/'  # 修正拼写错误
    MEDIA_ROOT = BASE_DIR / 'media/'
    
  • 修正Nginx配置的路径拼写和location规则
    Nginx配置里存在两处关键错误:

    1. 路径中的ninx-django是拼写错误,应为nginx-django;
    2. location /media缺少末尾斜杠,和MEDIA_URL的/media/不匹配,会导致路径拼接异常。
      修改后的Nginx配置:
    server {
        listen 80;
        server_name my_ip;
    
        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            autoindex on;
            alias /home/ubuntu/nginx-django/hoshnyetli_project/staticfiles/;
       }
        location /media/ {  # 添加末尾斜杠匹配MEDIA_URL
            autoindex on;
            alias /home/ubuntu/nginx-django/hoshnyetli_project/media/;  # 修正路径拼写错误
       }
    
        location / {
            include proxy_params;
            proxy_pass http://unix:/run/hoshniyetli.sock;
        }
    }
    

    修改完成后重启Nginx生效:sudo systemctl restart nginx

  • 检查媒体目录的权限
    确保Nginx进程(通常以www-data用户运行)能读取媒体目录及文件:

    # 设置目录所有者为www-data
    sudo chown -R www-data:www-data /home/ubuntu/nginx-django/hoshnyetli_project/media/
    # 设置目录权限为755,文件权限为644
    sudo chmod -R 755 /home/ubuntu/nginx-django/hoshnyetli_project/media/
    sudo find /home/ubuntu/nginx-django/hoshnyetli_project/media/ -type f -exec chmod 644 {} \;
    
  • 验证媒体文件实际路径
    确认上传的媒体文件确实存在于目标目录中,比如检查是否有测试文件:

    ls /home/ubuntu/nginx-django/hoshnyetli_project/media/
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:38:18