Search code examples
djangodjango-rest-framework

How to return image URL as prefix https:// in Django Rest Framework?


My django Rest API return image URL path http://blah/media/blah.jpg. But I want to return https://blahblah.

Is there any attribute in settings.py?

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

I Inserted this and tried

SECURE_SSL_REDIRECT = True

but it throws 301 code and nothing rendered.

Media setting

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Solution

  • For serving media files there are two ways to do:

    1. By serving media and static files using nginx, in that case you need to enable ssl in nginx and it will come as https://
    2. by returning media file path from rest framework like /media/image1.jpg and adding your domain at client side like https://mydomainxyz.com/media.image1.jpg

    When you activate SECURE_SSL_REDIRECT in django it redirects every request to https server. Django development server does not work on https. You will need nginx or apache server for that and enable ssl settings. This is the reason nothing is getting rendered. For more read here in django documentation