I'm currently working on a Django project that utilizes Docker, and I recently set up an SSL certificate using a containerized version of Certbot in order to secure my Django app through HTTPS. However, after implementing the SSL certificate and updating my nginx configuration, I began to experience the 'CSRF verification failed' error, which was not an issue before the setup. Previously, I was able to log into my Django app when it was using HTTP. What could be the cause of this problem?
My Django setting.
# settings.py
ALLOWED_HOSTS = ["*"]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
if DEBUG:
CORS_ALLOW_ALL_ORIGINS = True
else:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
'https://example.ph',
]
My previous nginx configuration.
upstream api {
server sinag_app:8000;
}
server {
listen 80;
location / {
proxy_pass http://api;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /static/ {
alias /static/;
}
}
My new nginx configuration with SSL certificate.
upstream api {
server sinag_app:8000;
}
server {
listen 80;
server_name ${DOMAIN};
location /.well-known/acme-challenge/ {
root /vol/www;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name ${DOMAIN};
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
include /etc/nginx/options-ssl-nginx.conf;
ssl_dhparam /vol/proxy/ssl-dhparams.pem;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
client_max_body_size 4G;
keepalive_timeout 5;
location /static/ {
alias /static/;
}
location / {
proxy_pass http://api;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
}
}