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

Docker部署DRF时,Django返回的Media URL异常如何解决?

解决Django返回媒体文件URL错误的问题

1. 修正Nginx反向代理配置

你的Nginx配置存在两处关键问题:一是listen 443 ssl等SSL配置被错误放在了location /块内,二是缺少传递外部域名和协议的代理头,同时未配置请求转发到Django容器的规则。修改后的完整server块如下:

server {
    server_name api.example.com www.api.example.com;
    access_log /var/log/nginx/api.example.com-access.log;
    error_log /var/log/nginx/api.example.com-error.log;

    # SSL配置必须放在server块层级
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    # 静态媒体文件直接由Nginx提供
    location /media/ {
        alias /opt/site_backend_docker/Site_Backend/apps/media/;
    }

    # 动态请求转发到Django容器
    location / {
        client_max_body_size 0;
        gzip off;
        proxy_read_timeout      300;
        proxy_connect_timeout   300;
        proxy_redirect          off;
        proxy_http_version 1.1;
        
        # 传递真实客户端IP和外部请求信息
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    Host                $host;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_set_header    X-Forwarded-Host    $host;
        
        # 替换为你的Django容器端口(比如6500)
        proxy_pass http://localhost:6500;
    }
}

server {
    if ($host = api.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name api.example.com www.api.example.com;
    listen 80;
    return 404; # managed by Certbot
}

2. 更新Django配置(settings.py)

添加以下配置,让Django信任Nginx作为反向代理,并基于代理头生成正确的外部URL:

# 允许你的域名访问
ALLOWED_HOSTS = ['api.example.com', 'www.api.example.com']

# 启用反向代理头支持
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# 可选:强制所有请求使用HTTPS
SECURE_SSL_REDIRECT = True

3. 重启服务生效

  1. 验证Nginx配置合法性:sudo nginx -t
  2. 重启Nginx:sudo systemctl restart nginx
  3. 重启Django容器,确保新配置加载

完成后,Django返回的ImageField URL会自动生成为https://api.example.com/media/path/to/file,与Nginx提供的访问地址一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:59:50