Django + Gunicorn + Nginx = CSRF cookie未设置

时间:2021-12-02 07:36:58

I've set up Django behind Nginx with Gunicorn, but when I try to log in to the admin panel, I get:

我在Nginx和Gunicorn后面设置了Django,但是当我尝试登录到管理面板时,我得到:

Forbidden (403)
CSRF verification failed. Request aborted.

Reason given for failure:
CSRF cookie not set.

This is weird because it works fine if I run it locally. However, behind nginx it fails when I run it using "python manage.py runserver 0.0.0.0:8000" and "python manage.py run_gunicorn".

这很奇怪,因为如果我在本地运行它,它会运行得很好。然而,在nginx的后面,当我使用“python管理”运行它时,它就失败了。py runserver 0.0.0:8000“和”python管理。py run_gunicorn”。

settings.py:

settings.py:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # CORS SUPPORT
    'corsheaders.middleware.CorsMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

nginx.conf:

nginx.conf:

server {
        listen 8080;
        server_name  example.com;
        access_log  /var/log/nginx/example.com.access.log;
        error_log  /var/log/nginx/example.com.error.log info;

        keepalive_timeout 5;
        location /assets/grappelli/ {
                alias /var/www/example.com/virtualenv/lib/python2.6/site-packages/grappelli/static/grappelli/;
        }

        location /assets/ { # STATIC_URL
                alias /var/www/example.com/PopcornHour/assets/; # STATIC_ROOT
                expires 30d;
        }

location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;
        proxy_pass http://localhost:8000/;
    }
    # what to serve if upstream is not available or crashes
    error_page 500 502 503 504 /media/50x.html;

}

Many thanks for your help!

非常感谢您的帮助!

1 个解决方案

#1


1  

I found out why it was failing -- even though I have Varnish disabled for this domain, it still messed with the headers and cookies, disabled it for now :)

我发现了它失败的原因——尽管我在这个领域已经禁用了清漆,但它仍然与标头和cookie混在一起,暂时禁用了它:)

#1


1  

I found out why it was failing -- even though I have Varnish disabled for this domain, it still messed with the headers and cookies, disabled it for now :)

我发现了它失败的原因——尽管我在这个领域已经禁用了清漆,但它仍然与标头和cookie混在一起,暂时禁用了它:)