Skip to main content

HTTPSRedirectMiddleware

The HTTPSRedirectMiddleware 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:
  1. Checks if the incoming request is using HTTP (not HTTPS)
  2. If HTTP, constructs the HTTPS equivalent URL
  3. Returns a 307 Temporary Redirect response to the HTTPS URL
  4. 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

With this configuration:
  • http://example.com/https://example.com/
  • http://example.com/api/users?page=2https://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:
  1. Option 1: Handle HTTPS redirect at the proxy level (recommended)
  2. Option 2: Ensure the proxy sets the X-Forwarded-Proto header 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
In these cases, you may not need 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

  1. Always use in production: HTTPS protects data in transit
  2. HSTS Headers: Consider adding HTTP Strict Transport Security headers
  3. Certificate Management: Ensure your SSL certificates are valid and up-to-date
  4. 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-Proto header 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