Enforce HTTPS Middleware

A snippet showing how to enforce HTTPS in Django with middleware.


# middleware.py

from django.conf import settings
from django.http import HttpResponsePermanentRedirect

class EnforceHTTPSMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Respect Django setting and proxy headers
        use_https = getattr(settings, 'ENFORCE_HTTPS', True)
        is_secure = request.is_secure() or request.META.get('HTTP_X_FORWARDED_PROTO') == 'https'

        if use_https and not is_secure and not settings.DEBUG:
            url = request.build_absolute_uri(request.get_full_path())
            secure_url = url.replace('http://', 'https://', 1)
            return HttpResponsePermanentRedirect(secure_url)

        return self.get_response(request)
  

# settings.py

MIDDLEWARE = [
    # ...
    'your_app.middleware.EnforceHTTPSMiddleware',
]

# Turn on HTTPS enforcement (disable in local dev if needed)
ENFORCE_HTTPS = True

# If you're behind a reverse proxy / load balancer that sets X-Forwarded-Proto:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Alternative (built-in) redirect:
# SECURE_SSL_REDIRECT = True
  

# Example curl tests

# Simulate HTTP request (should redirect to HTTPS in non-DEBUG environments)
$ curl -I http://example.com/
HTTP/1.1 301 Moved Permanently
Location: https://example.com/

# Confirm HTTPS works
$ curl -I https://example.com/
HTTP/1.1 200 OK
  
Explanation:
  • The middleware forces HTTPS by redirecting plain HTTP to the same URL with https://.
  • It respects proxy headers using SECURE_PROXY_SSL_HEADER and checks request.is_secure().
  • Skips redirects during development (DEBUG=True) so localhost stays simple.
  • You can also use Django's built‑in SECURE_SSL_REDIRECT=True instead of custom middleware if preferred.
  • Category Middleware
  • Total Views 900
  • Last Modified 03 March, 2026
  • Tags #middleware #https #security #ssl
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.