I'm trying to set up a registration form on my site using nginx and gunicorn with Django. I've got the registration working when I connect with http, but I get the following error over https:
CSRF verification failed. Request aborted.
Reason given for failure:
Referer checking failed - https://<domainname>/register does not match https://127.0.0.1:8000/.
In general, this can occur when there is a genuine Cross Site Request
Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function passes a request to the template's render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
My nginx config is as follows:
server {
listen 80 default_server;
server_name <domainname>.co.uk www.<domainname>.co.uk;
access_log off;
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
location /static/ {
alias /www/<domainname>/www/static/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
Does anyone know how to resolve this?
You pass the X-Forwarded-Host
header to gunicorn, but Django does not use this header by default. Django then uses the HTTP_HOST
header, which does not match the referrer.
To use the X-Forwarded-Host
header, set USE_X_FORWARDED_HOST
to True
in your settings.