3

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')
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
  • What is `MEDIA_URL` in your settings? – Alasdair Nov 27 '19 at 13:43
  • update question with settings – Anuj TBE Nov 27 '19 at 13:46
  • If `MEDIA_URL = '/media_/'` and your Django server is running on https://, then the media file should be https as well. If the Django server is running on http:// and you want the media file to be on https://, then use `MEDIA_URL = 'https://example.com/media_/'` – Alasdair Nov 27 '19 at 13:56

1 Answers1

15

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.

bug
  • 3,900
  • 1
  • 13
  • 24
  • Is it `X-Forwarded-Protocol`? I have `proxy_set_header X-Forwarded-Protocol $scheme;` in the nginx config. – Anuj TBE Nov 27 '19 at 13:59
  • Nope, it's `X-Forwarded-Proto`: https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ – bug Nov 27 '19 at 14:01
  • When I use this configuration, I get a Bad Request: Contradictory scheme headers. I'm guessing something is still saying the HTTP_X_FORWARD_PROTO = 'http'. Any idea what that could be? I'm also using django / nginx. – Alex Nov 28 '22 at 22:07