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).
Django provides built-in security settings that allow automatic redirection of HTTP requests to HTTPS and enforce secure cookies and headers.
# 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
# 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;
}
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.
Test how the SECURE_SSL_REDIRECT setting affects browser behavior below.