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
.
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Custom Authentication Login And Registration Using Laravel 8
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- Google Login or Sign In with Angular Application
- How to Convert MySQL Data to JSON using PHP
- How to change date format in PHP?
- Image Lazy loading Using Slick Slider
- Slick Slider Basic With Example
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- Slick Slider Center Mode With Example
- How to Scroll to an Element with Vue 3 and ?
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- Slick Slider Multiple Items With Example