[Solved]-CSRF verification Failed – Referer is insecure while host is secure

10👍

I had this error when I was switching from ssl setup to no ssl and forgot to remove last line from upstream configuration in nginx config:

  location / {
    proxy_pass http://127.0.0.1:8085;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host; #:8080;
    #proxy_set_header X-FORWARDED-PROTO https;

  }

6👍

Those lines in your settings.py file are fine on production because you’re using an SSL certificate attached to your domain. However, on local you’re probably using http://localhost:8000 or something similar. If you try to connect via https://localhost:{{YOUR_PORT_NUMBER}} you’ll most likely get an error like ERR_SSL_PROTOCOL_ERROR.

The issue is in lines 167-168 of django/django/middleware/csrf.py. When you’re using https on production, request.is_secure() is returning True…which requires that the HTTP_REFERER also be true or you’ll get the error you referenced.

One solution would be to adjust your settings.py file depending on whether you’re in your local or production environment. That way you can add those three lines to a settings_production.py file that imports other settings that are common to both localhost and your production server. Your localhost would use a different set of settings that don’t include those lines.

Leave a comment