我试图在我的网站上使用nginx和gunicorn与Django建立注册表单。当我连接http时,我的注册工作正常,但是我在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.
我的nginx配置如下:
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"';
}
}
有谁知道如何解决这个问题?
答案 0 :(得分:0)
您将X-Forwarded-Host
标头传递给gunicorn,但Django默认情况下不使用此标头。 Django然后使用HTTP_HOST
标题,它与引用者不匹配。
要使用X-Forwarded-Host
标题,请在设置中将USE_X_FORWARDED_HOST
设置为True
。