HTTPS, Secure Cookies & Headers
HTTPS encrypts all traffic between client and server. Secure cookies and security headers add additional protection layers. Django provides settings for all of these — you just need to enable them in production.
15 min•By Priygop Team•Updated 2026
HTTPS & Headers
- HTTPS — Encrypts traffic, required for production
- HSTS — Forces browsers to always use HTTPS
- Secure cookies — Only sent over HTTPS
- HttpOnly cookies — Not accessible via JavaScript
- X-Frame-Options — Prevents clickjacking
- Content-Type sniffing — Prevents MIME confusion
- Let's Encrypt — Free SSL certificates
- Cloudflare — Easy HTTPS + CDN setup
Secure Configuration
Secure Configuration
# Production HTTPS settings (settings.py)
# Force HTTPS
# SECURE_SSL_REDIRECT = True
# HTTP Strict Transport Security
# SECURE_HSTS_SECONDS = 31536000 # 1 year
# SECURE_HSTS_INCLUDE_SUBDOMAINS = True
# SECURE_HSTS_PRELOAD = True
# Secure cookies
# SESSION_COOKIE_SECURE = True # Session cookie HTTPS only
# CSRF_COOKIE_SECURE = True # CSRF cookie HTTPS only
# SESSION_COOKIE_HTTPONLY = True # No JS access to session
# SESSION_COOKIE_SAMESITE = 'Lax' # Prevent cross-site sending
# Security headers
# SECURE_CONTENT_TYPE_NOSNIFF = True # X-Content-Type-Options: nosniff
# X_FRAME_OPTIONS = 'DENY' # Prevent iframe embedding
# SECURE_REFERRER_POLICY = 'same-origin'
# In development (settings_dev.py)
# SECURE_SSL_REDIRECT = False
# SESSION_COOKIE_SECURE = False
# CSRF_COOKIE_SECURE = FalseTip
Tip
Enable SECURE_SSL_REDIRECT=True in production to force HTTPS. Set SECURE_HSTS_SECONDS for HTTP Strict Transport Security.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not setting SECURE_BROWSER_XSS_FILTER and SECURE_CONTENT_TYPE_NOSNIFF. These prevent common browser-based attacks.
Practice Task
Note
(1) Enable HSTS with SECURE_HSTS_SECONDS. (2) Set SECURE_SSL_REDIRECT. (3) Add Content-Security-Policy header.
Quick Quiz
Key Takeaways
- HTTPS encrypts all traffic between client and server.
- HTTPS — Encrypts traffic, required for production
- HSTS — Forces browsers to always use HTTPS
- Secure cookies — Only sent over HTTPS