title: Django CSRF Error Casused by Nginx X-Forwarded-host
body: <p>I've been working on a django app recently and it is finally ready to get deployed to a qa and production environment. Everything worked perfectly locally, but since adding the complexity of the real world deployment I've had a few issues.</p>
  
  <p>First my tech stack is a bit complicated. For deployments I am using aws for everything with my site deployed on multiple ec2's backed by a load balancer. The load balancer is secured with ssl, but the connections to the load balancer are forwarded to the ec2's over standard http on port 80. After hitting an ec2 on port 80 they are forwarded to a docker container on port 8000 (if you are unfamiliar with docker just consider it to be a standard vm). Inside the container nginx listens on port 8000, it handles a redirection for the static files in django and for web requests it forwards the request to django running on 127.0.0.1:8001. Django is being hosted by uwsgi listening on port 8001.</p>
  
  <pre><code>server {
      listen   8000;
      server_name localhost;
  
      location /static/ {
          alias /home/library/deploy/thelibrary/static/;
      }
  
      location / {
          proxy_set_header X-Forwarded-Host $host:443;
          proxy_pass http://127.0.0.1:8001/;
      }
  }
  </code></pre>
  
  <p>I use X-Forwarded host because I was having issues with redirects from google oauth and redirects to prompt the user to login making the browser request the url 127.0.0.1:8001 which will obviously not work. Within my settings.py file I also included </p>
  
  <pre><code>USE_X_FORWARDED_HOST = True
  </code></pre>
  
  <p>to force django to use the correct host for redirects.</p>
  
  <p>Right now general browsing of the site works perfectly, static files load, redirects work and the site is secured with ssl. The problem however is that CSRF verification fails.</p>
  
  <p>On a form submission I get the following error </p>
  
  <p>Referer checking failed - <a href="https://qa-load-balancer.com/projects/new" rel="nofollow">https://qa-load-balancer.com/projects/new</a> does not match <a href="https://qa-load-balancer.com:443/" rel="nofollow">https://qa-load-balancer.com:443/</a>.</p>
  
  <p>I'm really not sure what to do about this, its really through stackoverflow questions that I got everything working so far.</p>