Nginx – UWSGI, Django, nginx cookie issue – causes 405 Error

djangonginxuwsgi

I'm running django via uwsgi and nginx, and whenever my app tries to set a cookie, nginx displays a 405 error. The app works fine with apache, runserver or gunicorn, and uwsgi serves it normally except for the redirect problem.

I'm running uwsgi like so:

uwsgi --master --http-socket :8082 \
      --wsgi-file /var/django/mysite/apache/live.wsgi \
      --touch-reload /var/django/mysite/apache/live.wsgi

My live.wsgi file looks like this:

import os, sys

PROJECT_ROOT = '/var/django/mysite/'

directory = os.path.join(PROJECT_ROOT, 'src')
if not directory in sys.path:
    sys.path.insert(0, directory)

os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

nginx is proxying requests to 127.0.0.1:8082 for this site.

UPDATE: Bizarrely, the issue seems to be triggered by django's messages framework – removing django.contrib.messages.middleware.MessageMiddleware stops the error. This leads me to think that it's got nothing to do with redirects after all, and is instead something to do with the message that's created on object save in the django admin.

UPDATE 2: Some further digging reveals that it seems to be an issue with cookies being set – switching the messages framework to use the session backend stops the errors. I'm still at a loss as to why the uwsgi/nginx stack won't let django set cookies. I've updated the question to reflect that.

Best Answer

Ok, so it looks like increasing uwsgi buffer size to 16k has stopped the errors. I guess the django messages cookie is too large? I'm not sure which solution is best out of switching to session storage or increasing the buffer, but there you go.

My uwsgi command now looks like this:

uwsgi --master --http-socket :8082 \
      --wsgi-file /var/django/mysite/apache/live.wsgi \
      --touch-reload /var/django/mysite/apache/live.wsgi \
      --buffer-size 16384

According to the django messages docs,

Old messages are dropped if the cookie data size would exceed 4096 bytes.

So I guess it makes sense that the uwsgi buffer needs to be greater than this.