Force HTTPS On Flask Custom Domains

I have tried everything I can but I cant get Force HTTPS.

def before_request():

if not “https” in request.headers.get(“X-Forwarded-Proto”, “”):
url = request.url.replace(‘http://’, ‘https://’, 1)
code = 301
return redirect(url, code=code)

The above works when I’m not on the custom domain
but on the http://customdomain: request.headers.get(“X-Forwarded-Proto”, “”) returns https, http, http

Any help would be appicated, Thank you!

1 Like

You’ll want to force https client side unfortunately since the communication from the server to your app is unaffected when you redirect.

Thank you so much @javaarchive! You saved my life!

For anyone else wanting to redirect through client side:

// current url: http://example.
if(window.location.href.substr(0,5) !== ‘https’){
window.location.href = window.location.href.replace(‘http’, ‘https’);
} // new url: https://example.

Answer From: Ankit Chauhan on Stack Overflow

1 Like

Probably the better solution:

1 Like

If you have to force HTTPS client side, there isn’t much of a point as the content of the page has already been delivered without encryption.

1 Like

This can work too:

  if (location.protocol != "https:") {
    location.href =
      "https:" +

the catch with that is if you have something like it’ll also modify the second part.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.