1 ===========================================
2 How to use Django with FastCGI, SCGI or AJP
3 ===========================================
5 Although the `current preferred setup`_ for running Django is Apache_ with
6 `mod_python`_, many people use shared hosting, on which protocols such as
7 FastCGI, SCGI or AJP are the only viable options. In some setups, these protocols
8 also allow better security -- and, possibly, better performance -- than mod_python.
12 This document primarily focuses on FastCGI. Other protocols, such as SCGI
13 and AJP, are also supported, through the ``flup`` Python package. See the
14 "Protocols" section below for specifics about SCGI and AJP.
16 Essentially, FastCGI is an efficient way of letting an external application
17 serve pages to a Web server. The Web server delegates the incoming Web requests
18 (via a socket) to FastCGI, which executes the code and passes the response back
19 to the Web server, which, in turn, passes it back to the client's Web browser.
21 Like mod_python, FastCGI allows code to stay in memory, allowing requests to be
22 served with no startup time. Unlike mod_python (or `mod_perl`_), a FastCGI
23 process doesn't run inside the Web server process, but in a separate,
26 .. _current preferred setup: ../modpython/
27 .. _Apache: http://httpd.apache.org/
28 .. _mod_python: http://www.modpython.org/
29 .. _mod_perl: http://perl.apache.org/
31 .. admonition:: Why run code in a separate process?
33 The traditional ``mod_*`` arrangements in Apache embed various scripting
34 languages (most notably PHP, Python and Perl) inside the process space of
35 your Web server. Although this lowers startup time -- because code doesn't
36 have to be read off disk for every request -- it comes at the cost of
37 memory use. For mod_python, for example, every Apache process gets its own
38 Python interpreter, which uses up a considerable amount of RAM.
40 Due to the nature of FastCGI, it's even possible to have processes that run
41 under a different user account than the Web server process. That's a nice
42 security benefit on shared systems, because it means you can secure your
43 code from other users.
48 Before you can start using FastCGI with Django, you'll need to install flup_,
49 which is a Python library for dealing with FastCGI. Version 0.5 or newer should
52 .. _flup: http://www.saddi.com/software/flup/
54 Starting your FastCGI server
55 ============================
57 FastCGI operates on a client-server model, and in most cases you'll be starting
58 the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or
59 otherwise) only contacts your Django-FastCGI process when the server needs a
60 dynamic page to be loaded. Because the daemon is already running with the code
61 in memory, it's able to serve the response very quickly.
65 If you're on a shared hosting system, you'll probably be forced to use
66 Web server-managed FastCGI processes. See the section below on running
67 Django with Web server-managed processes for more information.
69 A Web server can connect to a FastCGI server in one of two ways: It can use
70 either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a
71 TCP socket. What you choose is a manner of preference; a TCP socket is usually
72 easier due to permissions issues.
74 To start your server, first change into the directory of your project (wherever
75 your ``manage.py`` is), and then run ``manage.py`` with the ``runfcgi`` option::
77 ./manage.py runfcgi [options]
79 If you specify ``help`` as the only option after ``runfcgi``, it'll display a
80 list of all the available options.
82 You'll need to specify either a ``socket``, ``protocol`` or both ``host`` and ``port``.
83 Then, when you set up your Web server, you'll just need to point it at the host/port
84 or socket you specified when starting the FastCGI server.
89 Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and
90 `AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred
91 protocol by using the ``protocol=<protocol_name>`` option with
92 ``./manage.py runfcgi`` -- where ``<protocol_name>`` may be one of: ``fcgi``
93 (the default), ``scgi`` or ``ajp``. For example::
95 ./manage.py runfcgi protocol=scgi
97 .. _flup: http://www.saddi.com/software/flup/
98 .. _fastcgi: http://www.fastcgi.com/
99 .. _SCGI: http://python.ca/scgi/protocol.txt
100 .. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
105 Running a threaded server on a TCP port::
107 ./manage.py runfcgi method=threaded host=127.0.0.1 port=3033
109 Running a preforked server on a Unix domain socket::
111 ./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
113 Run without daemonizing (backgrounding) the process (good for debugging)::
115 ./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock maxrequests=1
117 Stopping the FastCGI daemon
118 ---------------------------
120 If you have the process running in the foreground, it's easy enough to stop it:
121 Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when
122 you're dealing with background processes, you'll need to resort to the Unix
125 If you specify the ``pidfile`` option to your ``manage.py runfcgi``, you can
126 kill the running FastCGI daemon like this::
130 ...where ``$PIDFILE`` is the ``pidfile`` you specified.
132 To easily restart your FastCGI daemon on Unix, try this small shell script::
136 # Replace these three settings.
137 PROJDIR="/home/user/myproject"
138 PIDFILE="$PROJDIR/mysite.pid"
139 SOCKET="$PROJDIR/mysite.sock"
142 if [ -f $PIDFILE ]; then
143 kill `cat -- $PIDFILE`
147 exec /usr/bin/env - \
148 PYTHONPATH="../python:.." \
149 ./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE
154 To use Django with Apache and FastCGI, you'll need Apache installed and
155 configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache
156 documentation for instructions.
158 Once you've got that set up, point Apache at your Django FastCGI instance by
159 editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two
162 * Use the ``FastCGIExternalServer`` directive to specify the location of
164 * Use ``mod_rewrite`` to point URLs at FastCGI as appropriate.
166 .. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
168 Specifying the location of the FastCGI server
169 ---------------------------------------------
171 The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI
172 server. As the `FastCGIExternalServer docs`_ explain, you can specify either a
173 ``socket`` or a ``host``. Here are examples of both::
175 # Connect to FastCGI via a socket / named pipe.
176 FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock
178 # Connect to FastCGI via a TCP host/port.
179 FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033
181 In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't
182 actually have to exist. It's just a URL used by the Web server internally -- a
183 hook for signifying which requests at a URL should be handled by FastCGI. (More
184 on this in the next section.)
186 .. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
188 Using mod_rewrite to point URLs at FastCGI
189 ------------------------------------------
191 The second step is telling Apache to use FastCGI for URLs that match a certain
192 pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to
193 ``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer``
194 directive, as explained in the previous section).
196 In this example, we tell Apache to use FastCGI to handle any request that
197 doesn't represent a file on the filesystem and doesn't start with ``/media/``.
198 This is probably the most common case, if you're using Django's admin site::
200 <VirtualHost 12.34.56.78>
201 ServerName example.com
202 DocumentRoot /home/user/public_html
203 Alias /media /home/user/python/django/contrib/admin/media
205 RewriteRule ^/(media.*)$ /$1 [QSA,L,PT]
206 RewriteCond %{REQUEST_FILENAME} !-f
207 RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L]
210 .. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
215 lighttpd is a lightweight Web server commonly used for serving static files. It
216 supports FastCGI natively and, thus, is a good choice for serving both static
217 and dynamic pages, if your site doesn't have any Apache-specific needs.
219 Make sure ``mod_fastcgi`` is in your modules list, somewhere after
220 ``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll
221 probably want ``mod_alias`` as well, for serving admin media.
223 Add the following to your lighttpd config file::
225 server.document-root = "/home/user/public_html"
229 # Use host / port instead of socket for TCP fastcgi
230 # "host" => "127.0.0.1",
232 "socket" => "/home/user/mysite.sock",
233 "check-local" => "disable",
238 "/media/" => "/home/user/django/contrib/admin/media/",
242 "^(/media.*)$" => "$1",
243 "^/favicon\.ico$" => "/media/favicon.ico",
244 "^(/.*)$" => "/mysite.fcgi$1",
247 Running multiple Django sites on one lighttpd
248 ---------------------------------------------
250 lighttpd lets you use "conditional configuration" to allow configuration to be
251 customized per host. To specify multiple FastCGI sites, just add a conditional
252 block around your FastCGI config for each site::
254 # If the hostname is 'www.example1.com'...
255 $HTTP["host"] == "www.example1.com" {
256 server.document-root = "/foo/site1"
263 # If the hostname is 'www.example2.com'...
264 $HTTP["host"] == "www.example2.com" {
265 server.document-root = "/foo/site2"
272 You can also run multiple Django installations on the same site simply by
273 specifying multiple entries in the ``fastcgi.server`` directive. Add one
274 FastCGI host for each.
276 Running Django on a shared-hosting provider with Apache
277 =======================================================
279 Many shared-hosting providers don't allow you to run your own server daemons or
280 edit the ``httpd.conf`` file. In these cases, it's still possible to run Django
281 using Web server-spawned processes.
285 If you're using Web server-spawned processes, as explained in this section,
286 there's no need for you to start the FastCGI server on your own. Apache
287 will spawn a number of processes, scaling as it needs to.
289 In your Web root directory, add this to a file named ``.htaccess`` ::
291 AddHandler fastcgi-script .fcgi
293 RewriteCond %{REQUEST_FILENAME} !-f
294 RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
296 Then, create a small script that tells Apache how to spawn your FastCGI
297 program. Create a file ``mysite.fcgi`` and place it in your Web directory, and
298 be sure to make it executable::
303 # Add a custom Python path.
304 sys.path.insert(0, "/home/user/python")
306 # Switch to the directory of your project. (Optional.)
307 # os.chdir("/home/user/myproject")
309 # Set the DJANGO_SETTINGS_MODULE environment variable.
310 os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
312 from django.core.servers.fastcgi import runfastcgi
313 runfastcgi(method="threaded", daemonize="false")
315 Restarting the spawned server
316 -----------------------------
318 If you change any Python code on your site, you'll need to tell FastCGI the
319 code has changed. But there's no need to restart Apache in this case. Rather,
320 just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the
321 file will change. When Apache sees the file has been updated, it will restart
322 your Django application for you.
324 If you have access to a command shell on a Unix system, you can accomplish this
325 easily by using the ``touch`` command::
329 Serving admin media files
330 =========================
332 Regardless of the server and configuration you eventually decide to use, you will
333 also need to give some thought to how to serve the admin media files. The
334 advice given in the modpython_ documentation is also applicable in the setups
337 .. _modpython: ../modpython/#serving-the-admin-files