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
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- How to Convert MySQL Data to JSON using PHP
- Custom Authentication Login And Registration Using Laravel 8
- Slick Slider Basic With Example
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- How to change date format in PHP?
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- Slick Slider Center Mode With Example
- How to Scroll to an Element with Vue 3 and ?
- Image Lazy loading Using Slick Slider
- Calculate Subtotal On Quantity Increment in Woocommerce Single Product Page
- Slick Slider Multiple Items With Example
Share