← Back to Chapters

Enforcing HTTPS in Django

? Enforcing HTTPS in Django

? Quick Overview

HTTPS ensures encrypted communication between a user's browser and a server. In Django applications, enforcing HTTPS protects sensitive data and prevents attacks such as man-in-the-middle (MITM).

? Key Concepts

  • HTTPS: Secure HTTP using SSL/TLS encryption.
  • SSL/TLS: Cryptographic protocols for secure communication.
  • HSTS: Forces browsers to always use HTTPS.

? Syntax / Theory

Django provides built-in security settings that allow automatic redirection of HTTP requests to HTTPS and enforce secure cookies and headers.

? Code Example(s)

? View Code Example
# Force HTTPS and secure cookies in Django
SECURE_SSL_REDIRECT = True
SECURE_COOKIE_HTTPONLY = True
SECURE_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
? View Code Example
# Nginx configuration to enable HTTPS
server {
    listen 443 ssl;
    server_name yourdomain.com;
    ssl_certificate /etc/ssl/certs/yourdomain.crt;
    ssl_certificate_key /etc/ssl/private/yourdomain.key;
    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}
server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$host$request_uri;
}

? Live Output / Explanation

When users access your site using HTTP, Django and the web server automatically redirect them to HTTPS. Browsers display a padlock icon indicating a secure connection.

? Interactive / Visual Concept

Test how the SECURE_SSL_REDIRECT setting affects browser behavior below.

Django Settings (settings.py)
?

Server Status

Enter a URL and click Go.

? Use Cases

  • User authentication and login pages
  • Payment and checkout systems
  • APIs handling sensitive user data
  • Admin dashboards and control panels

✅ Tips & Best Practices

  • Always enforce HTTPS across the entire site.
  • Use strong TLS versions (1.2 or 1.3).
  • Enable HSTS only after HTTPS is fully working.

? Try It Yourself

  • Enable HTTPS locally using self-signed certificates.
  • Test HTTP to HTTPS redirection in production.
  • Inspect browser security headers.