[Django]-Bad request 400: nginx / gunicorn

88👍

I had the same problem and adding ALLOWED_HOSTS = ("yourdomain.com",) to settings fixed it.

UPDATE: there few other possibilities:

  1. Nginx (or whatever web server you use) doesn’t pass the $host variable to the app
  2. Host contains underscores

See details: https://blog.anvileight.com/posts/how-to-fix-bad-request-400-in-django/

7👍

As I was having the same issue (400 error code when trying to share with vagrant share), I stumble upon this question. The answer and comments are right, as the obvious solution is to set ALLOWED_HOSTS list, but I was already setting it correctly (I thought).

I can’t speak for nginx as I’m running this on apache2, but here’s what solved the issue:

  1. Take a look at the ALLOWED_HOSTS doc to find what’s best for your case.

  2. With vagrant, you might find it useful to accept all the vagrantshare.com subdomain, so just add '.vagrantshare.com' (notice the dot) to the ALLOWED_HOSTS list.

  3. Not sure if it is really necessary, but I changed the modified date of the wsgi.py file

    touch wsgi.py
    
  4. As I’m using apache2, I needed to restart the service.

    sudo service apache2 restart
    

And then it worked.

1👍

I ran into this issue. It was because I forgot to add the proxy_set_header settings in the nginx config:

proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

So Django didn’t see the original hostname that was requested, so it didn’t match with what was in ALLOWED_HOSTS. Then it gave back the 400 response.

After adding this to my nginx config (at the spot where you do the proxy_pass to Gunicorn) and then restarting nginx, it worked.

More info: https://docs.gunicorn.org/en/stable/deploy.html#nginx-configuration

Leave a comment