How to Serve Cloudinary with HTTPS on Django

Cloudinary’s documentation states that their client side libraries can automatically detect the protocol used in a page and generate HTTP/S urls for the image tags accordingly. This, of course, doesn’t apply to server side code, for which there’s no apt documentation on this matter.

In Cloudinary’s Django library, there are three ways in which you can define your site specific parameters:

  • A dictionary called CLOUDINARY that you can set in your settings.py.
  • The CLOUDINARY_CLOUD_NAME environment variable.
  • The CLOUDINARY_URL environment variable.

Although not mentioned in the documentation, the CLOUDINARY_URL environment variable can take query paramters, and these would be added to the cloudinary object that generates the urls within the Django templates. So to make sure that all requests to Cloudinary are made with HTTPS, all you have to do is set the CLOUDINARY_URL variable with the query parameter ‘secure’ and the value ‘True’, like so:

export CLOUDINARY_URL=cloudinary://123456789012345:abcdefghijklmnop-qrstuvwxyz@abcdefgh?secure=True

Just make sure to replace the fake API key, API secret and cloud name I typed above with your own.

This approach is not so great, though. It forces us to make sure we include the extra query param if we’ll ever need to change the Cloudinary URL in the future, and because it’s not in the code, we can only have all our pages transferred securely or none at all.

An alternative would be to use the CLOUDINARY dict that we can set under settings.py, but that method has a disadvantage as well – it doesn’t play nicely with the other environment variables. In fact, Cloudinary’s Django library regards the three approaches specified above for entering site preferences as exclusionary, so if we set the CLOUDINARY dict under settings.py, the CLOUDINARY_URL will not even be looked at. Considering the fact that under platforms such as Heroku, an environment variable is the preferable route, we’re basically left with nothing but bad choices.

Luckily, the cloudinary object used to generate image links is just python code, the intantiation method of which takes keyword arguments that would be added to the same dict used for storing the site specific values from the inputs mentioned above. So to set Cloudinary to use secure URLs, all that’s required are the following two lines in your settings.py:


import cloudinary
cloudinary.config(secure=True)

That’s it! Your Cloudinary URLs will now always be loaded with HTTPS. Because this is just python code, you can alter it to use secure or unsecure URLs according to different views (just make sure to do that inside view functions and not in settings.py).

| The missing configuration statement that’s required to get Cloudinary’s Python library to work on HTTPS-enabled websites.