PYTHON
Enforce HTTP Strict Transport Security (HSTS) in Flask
Add the HSTS header to your Flask application to force secure HTTPS connections, protecting against SSL stripping attacks and ensuring transport layer security.
from flask import Flask, redirect, request
app = Flask(__name__)
# Middleware to enforce HTTPS and HSTS
@app.before_request
def enforce_https_and_hsts():
if request.is_secure:
# Add HSTS header only for HTTPS requests
# max-age: How long (in seconds) the browser should remember to only use HTTPS
# includeSubDomains: Apply HSTS to all subdomains
# preload: Opt-in for browser HSTS preload lists (requires strict max-age and includeSubDomains)
app.config['HSTS_HEADERS'] = 'max-age=31536000; includeSubDomains; preload'
else:
# Redirect HTTP to HTTPS
if request.url.startswith('http://'):
# Ensure the redirect uses the same host and path
# For production, replace 'your_domain.com' with the actual domain
secure_url = request.url.replace('http://', 'https://', 1)
return redirect(secure_url, code=301)
@app.after_request
def add_hsts_header(response):
if 'HSTS_HEADERS' in app.config:
response.headers['Strict-Transport-Security'] = app.config['HSTS_HEADERS']
return response
@app.route('/')
def index():
return "<h1>Welcome! This site enforces HSTS.</h1>"
@app.route('/secure')
def secure_page():
return "<p>This is a secure page.</p>"
if __name__ == '__main__':
# In production, always run with HTTPS (e.g., behind a reverse proxy like Nginx or Apache)
# app.run(debug=False, ssl_context='adhoc') # For development with self-signed SSL
app.run(debug=True) # For basic local testing (will redirect to HTTPS if you try HTTP)
How it works: This Flask snippet demonstrates how to enforce HTTP Strict Transport Security (HSTS) for your web application. HSTS is a security policy that helps protect websites against man-in-the-middle attacks, such as SSL stripping. The `@app.before_request` hook checks if the request is secure (HTTPS); if not, it redirects to HTTPS. For secure requests, it sets a `Strict-Transport-Security` header in the `@app.after_request` hook. The `max-age` directive tells browsers to remember to access your site only via HTTPS for a specified duration, while `includeSubDomains` extends this policy to subdomains, and `preload` allows inclusion in browser HSTS preload lists for even stronger protection.