Menu Close

How to redirect to https from http with Python Flask?

Codeamend

Sometimes, we want to redirect to https from http with Python Flask.

In this article, we’ll look at how to redirect to https from http with Python Flask.

How to redirect to https from http with Python Flask?

To redirect to https from http with Python Flask, we redirect from the http URL to the https URL with request.url.replace.

For instance, we write

@app.before_request
def before_request():
    if not request.is_secure:
        url = request.url.replace("http://", "https://", 1)
        code = 301
        return redirect(url, code=code) 

to apply the @app.before_request decorator to the before_request function to call it before each request.

In it, we check if a https request is made with request.is_secure.

If it False, then we call request.url.replace to replace 'http://' with 'https://' in the URL.

We call redirect with the new url with 'https://' and we set the response code to 301 to do a 301 redirect to the https URL from the http URL.

Conclusion

To redirect to https from http with Python Flask, we redirect from the http URL to the https URL with request.url.replace.

Posted in Python

You can also read...