neithere

Python, Music, Laziness

Nginx + FastCGI + Django

date
Updates: 2008-12-13, 2009-07-19

Environment

In late 2008 I was migrating a couple of Django sites from Apache to nginx. I had chosen FastCGI as the glue between the framework and the web server.

Tested software versions:

  • Django (1.0+, pre-1.1)
  • flup (1.0.1, 1.0.3)
  • nginx (0.6.35, 0.7.26, 0.7.61, 0.8.5)

Everything was OK except for one thing:

Problem

Django would:

  1. display homepage regardless of the real path, or even
  2. fall into an endless loop.

...which was tracked down to the more concrete problem:

Django could not determine the PATH_INFO environment variable.

Solution

No problem-related information could be found in logs.

Quickly I found out that Django needs PATH_INFO to be set to $fastcgi_script_name, but strangely adding this param had no impact on Django’s behaviour.

After hours and hours of extensive googling and intensive playing with various combinations of settings I came up with the solution (or rather a workaround) that worked on any system. Add this to nginx config:

fastcgi_param SCRIPT_NAME "";
fastcgi_param PATH_INFO $fastcgi_script_name;

I.e. if you don’t reset SCRIPT_NAME, then PATH_INFO will not be set. I don’t know why.

One more quirk

Sometimes you can face another problem: nginx cannot serve static files (returns 403 Forbidden). The solution is to ensure that it can read all directories in the absolute path (i.e. you must set +x for each directory level).

A couple of hints