Force HTTPS django

So I am trying to make my Django project default to https using the SSL and HSTS settings in the docs. But whenever I try it- it won’t work or give me a redirect error.

Wierd eh?

So does anyone know how this can be fixed at all? Or any coding snippets to help solve this?

Just to clarify, the issue is that using the code in the Docs doesn’t work and I want to force HTTPS

I have no experience with django, but i have made this code snippet to help you.

HTML

<body onload="start()">

JAVASCRIPT

function start() {
  var x = location.protocol;
  if (x == "http:"){
    window.location.protocol = 'https:'
  }
}
2 Likes

Do we have any Django specialists here?

3 Likes

Are you use a reverse proxy or a web server like Apache or Nginx in front of Django? There doesn’t seem to be a great way to do this other than using server software like this or the method you linked.

Also, @LankyBox01 forcing HTTPS in client side JavaScript also isn’t a great idea as the data has already been sent over HTTP.

3 Likes

Hi @RiversideRocks, I’m just using glitch which I think uses Apache. I think by default glitch uses a proxy.

Let’s say I try the method I linked, it will always give me a TOO_MANY_REDIRECTS error or not work at all. Perhaps there is a way to configure apache or Django to default to https using a configuration file?

Could you track down what the redirects are? Maybe it’s going in a loop.

1 Like

It still could help. If you do this and the site has an account system this could prevent people entering passwords & tokens over HTTP.

If you get a redirect error, it may be because you have set SECURE_PROXY_SSL_HEADER to an incorrect value.
If you have copied the example from the docs without modifications, it will not work on Glitch, as the value of the X-Forwarded-Proto header, when using a secure connection, is set to https,http,http.
It should therefore be:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https,http,http')
4 Likes

thanks everyone- this has helped a lot! :smiley:

2 Likes