Flask - Force HTTP to redirect to HTTPS
by
Jeremy Canfield |
Updated: August 26 2023
| Flask articles
The following function can be used to force all routes in your view to be redirected to HTTPS.
@auth.before_request
def force_https():
if not request.is_secure:
url = request.url.replace('http://', 'https://', 1)
return redirect(url, code=301)
Or, the Flask Security Guide recommends using Flask-Talisman. The pip install command can be used to install flask-talisman.
pip install flask-talisman
Or, you can specify the version to install
pip install flask-talisman==1.0.0
Or, better yet, use a requirements.txt file.
flask-talisman==1.0.0
And then install the packages using the requirements.txt file.
pip install --requirement requirements.txt
In your controller, import flask_talisman can then use the Talisman module to force HTTPS
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
Talisman(app)
Did you find this article helpful?
If so, consider buying me a coffee over at