Bad Request (400) - Django, Nginx, Gunicorn on Debian 7

July 23, 2014 10.8k views

I'm trying to run Django on Nginx + Unicorn (Debian 7) as described in this tutorial: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps

This is how my Nginx looks like:

server{
        server_name 146.185.185.212;

        access_log off;

        location /static/ {
                alias opt/myenv/static/;
        }

        location / {
                proxy_pass http://127.0.0.1:8001;
                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 N$
        }
}

This is how I start Gunicorn:

gunicorn --bind 127.0.0.1:8001 projname.wsgi:application

The problem is that i keep getting : Bad Request (400) in the browser.

Does anyone have any clue on how to fix this?

4 Answers

Try adding

proxy_set_header Host $host;

to your nginx config and restarting nginx. Does that fix it?

Make sure ALLOWED_HOSTS contains your domain name.

Nope, same error. This is how my nginx looks like now:

server {
       server_name 146.185.185.212;

       access_log off;

       location /static/ {
                alias opt/myenv/static/;
       }

       location / {
                proxy_pass http://127.0.0.1:8001;
                proxy_set_header X-Forwarded-Host $server_name;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM N$
        }
}

This is my ALLOWED_HOSTS in settings.py:

ALLOWED_HOSTS = ['146.185.185.212']
  • Have you restarted nginx and gunicorn after making the changes?

  • Yes, if by restart you mean

    service nginx restart
    

    and simply killing the gunicorn background job and starting it again.

    Has anyone actually got this to work? I've seen around a few users struggling with similar issues and no resolution

  • I was experiencing this same error until I added the proxy_set_header Host $host; line. I restarted nginx and it seemed to work.

    Are you requesting 146.185.185.212:8001 in your browser or 146.185.185.212:80?

Here's how you fix it:

  • You must first make sure you have proxy_set_header Host $host; & the server-IP:8001 in the proxy_pass instead of 127.0.0.1:8001 under the location directive in your nginx project config file.

  • Open your Django project settings.py in /opt/projectname/projectname/projectname.setting.py or /opt/projectname/projectname/projectname/projectname/settings.py (notice added project directory) and set the ALLOWED_HOSTS to ["yourserverip"]. Example: ALLOWED_HOSTS = ["25.22.12.21"]

  • If you have started Gunicorn, then while in virtualenv, type ps ax|grep gunicorn, It will give you a list of gunicorn processes, on the left you will see the process id of these processes, you may kill each of them my typing kill xxxx and then make sure Gunicorn is not running by typing bg, It will not return the following "Job 1 in already in background".

  • Finally, service nginx restart and it should work.

Here are my files for example:

/etc/nginx/sites-available/projectname (nginx project config file)

server {
    listen      80;
    server_name 25.22.12.21;

    access_log off;

    location /static/ {
        alias /opt/projectname/static/;
    }

    location / {
        proxy_set_header Host $host;
        proxy_pass http://25.22.12.21:8001;
        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"';
    }
}

/opt/projectname/projectname/projectname/settings.py (project settings.py)

"""
Django settings for robust project.

Generated by 'django-admin startproject' using Django 1.8.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["25.22.12.21"]


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'projectname.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'projectname.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'toordb',
    'USER': 'root',
    'PASSWORD': 'root',
    'HOST': 'localhost',
    'PORT': '3306',
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = '/opt/projectname/static/'

STATIC_URL = '/static/'

Hope this helps,
Basit

Have another answer? Share your knowledge.