HTTPSRedirectMiddleware
TheHTTPSRedirectMiddleware enforces HTTPS by redirecting all incoming HTTP requests to HTTPS. This is essential for security in production environments.
Usage
Parameters
This middleware does not take any configuration parameters. It automatically redirects all HTTP requests to their HTTPS equivalent.How It Works
The middleware:- Checks if the incoming request is using HTTP (not HTTPS)
- If HTTP, constructs the HTTPS equivalent URL
- Returns a 307 Temporary Redirect response to the HTTPS URL
- If already HTTPS, passes the request through normally
Redirect Behavior
- Status Code: Uses 307 Temporary Redirect to preserve the HTTP method
- URL Preservation: Maintains the full path, query parameters, and fragment
- Port Handling: Automatically handles port numbers in the URL
Examples
Basic Usage
http://example.com/→https://example.com/http://example.com/api/users?page=2→https://example.com/api/users?page=2
Conditional HTTPS Enforcement
Combined with Other Security Middleware
Deployment Considerations
Reverse Proxy/Load Balancer
If your application is behind a reverse proxy (nginx, Apache) or load balancer that terminates SSL:- Option 1: Handle HTTPS redirect at the proxy level (recommended)
- Option 2: Ensure the proxy sets the
X-Forwarded-Protoheader so the middleware can detect the original scheme
Cloud Platforms
Many cloud platforms handle HTTPS termination:- AWS ELB/ALB: Terminates SSL at the load balancer
- Google Cloud Load Balancer: Terminates SSL at the load balancer
- Azure Application Gateway: Terminates SSL at the gateway
- Heroku: Automatically handles HTTPS routing
HTTPSRedirectMiddleware as the platform handles it.
Development Environment
Don’t use this middleware in local development unless you’ve set up local SSL certificates:Security Best Practices
- Always use in production: HTTPS protects data in transit
- HSTS Headers: Consider adding HTTP Strict Transport Security headers
- Certificate Management: Ensure your SSL certificates are valid and up-to-date
- Redirect at the edge: When possible, handle redirects at the CDN or load balancer level for better performance
HSTS (HTTP Strict Transport Security)
After implementing HTTPS redirects, consider adding HSTS headers to tell browsers to always use HTTPS:Common Issues
Redirect Loops
If you experience redirect loops:- Check if your reverse proxy is configured correctly
- Ensure
X-Forwarded-Protoheader is set properly - Verify SSL termination is happening at the expected layer
Mixed Content Warnings
After enabling HTTPS:- Update all internal links to use HTTPS or relative URLs
- Ensure external resources (CDNs, APIs) are also loaded via HTTPS
- Check browser console for mixed content warnings