djangodjango-media

Django MEDIA_URL returns http instead of https


I'm using Django 2.2.x and DRF.

I have a model with FileField

file = models.FileField(upload_to=get_media_upload_path)

Files are uploading but on access the obj.file, it gives URL without HTTPS

http://example.com/media/image.jpg

I want it to be

https://example.com/media/image.png

Redirect is already setup in nginx config. But I want the response URL with https.

settings

MEDIA_URL = '/media_/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root')

Solution

  • First, make sure Nginx is sending the X-Forwarded-Proto header, it should be set to:

    proxy_set_header X-Forwarded-Proto https;
    

    Then in your Django settings add the following:

    USE_X_FORWARDED_HOST = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    

    In this way you will instruct Django to use the proto passed by the proxy.