Fixed #4764 -- Added reference to Locale middleware in middleware docs. Thanks, dan...
[django.git] / docs / fastcgi.txt
blob81888bba764f69b50b1ecc600975f6b095faa9aa
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.
10 .. admonition:: Note
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,
24 persistent process.
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.
45 Prerequisite: flup
46 ==================
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. Make sure to use the latest
50 Subversion snapshot of flup, as some users have reported stalled pages with
51 older flup versions.
53 .. _flup: http://www.saddi.com/software/flup/
55 Starting your FastCGI server
56 ============================
58 FastCGI operates on a client-server model, and in most cases you'll be starting
59 the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or
60 otherwise) only contacts your Django-FastCGI process when the server needs a
61 dynamic page to be loaded. Because the daemon is already running with the code
62 in memory, it's able to serve the response very quickly.
64 .. admonition:: Note
66     If you're on a shared hosting system, you'll probably be forced to use
67     Web server-managed FastCGI processes. See the section below on running
68     Django with Web server-managed processes for more information.
70 A Web server can connect to a FastCGI server in one of two ways: It can use
71 either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a
72 TCP socket. What you choose is a manner of preference; a TCP socket is usually
73 easier due to permissions issues.
75 To start your server, first change into the directory of your project (wherever
76 your ``manage.py`` is), and then run ``manage.py`` with the ``runfcgi`` option::
78     ./manage.py runfcgi [options]
80 If you specify ``help`` as the only option after ``runfcgi``, it'll display a
81 list of all the available options.
83 You'll need to specify either a ``socket``, ``protocol`` or both ``host`` and ``port``.
84 Then, when you set up your Web server, you'll just need to point it at the host/port
85 or socket you specified when starting the FastCGI server.
87 Protocols
88 ---------
90 Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and
91 `AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred
92 protocol by using the ``protocol=<protocol_name>`` option with
93 ``./manage.py runfcgi`` -- where ``<protocol_name>`` may be one of: ``fcgi``
94 (the default), ``scgi`` or ``ajp``. For example::
96     ./manage.py runfcgi --protocol=scgi
98 .. _flup: http://www.saddi.com/software/flup/
99 .. _fastcgi: http://www.fastcgi.com/
100 .. _SCGI: http://python.ca/scgi/protocol.txt
101 .. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
103 Examples
104 --------
106 Running a threaded server on a TCP port::
108     ./manage.py runfcgi method=threaded host=127.0.0.1 port=3033
110 Running a preforked server on a Unix domain socket::
112     ./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
114 Run without daemonizing (backgrounding) the process (good for debugging)::
116     ./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock
118 Stopping the FastCGI daemon
119 ---------------------------
121 If you have the process running in the foreground, it's easy enough to stop it:
122 Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when
123 you're dealing with background processes, you'll need to resort to the Unix
124 ``kill`` command.
126 If you specify the ``pidfile`` option to your ``manage.py runfcgi``, you can
127 kill the running FastCGI daemon like this::
129     kill `cat $PIDFILE`
131 ...where ``$PIDFILE`` is the ``pidfile`` you specified.
133 To easily restart your FastCGI daemon on Unix, try this small shell script::
135     #!/bin/bash
137     # Replace these three settings.
138     PROJDIR="/home/user/myproject"
139     PIDFILE="$PROJDIR/mysite.pid"
140     SOCKET="$PROJDIR/mysite.sock"
142     cd $PROJDIR
143     if [ -f $PIDFILE ]; then
144         kill `cat -- $PIDFILE`
145         rm -f -- $PIDFILE
146     fi
148     exec /usr/bin/env - \
149       PYTHONPATH="../python:.." \
150       ./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE
152 Apache setup
153 ============
155 To use Django with Apache and FastCGI, you'll need Apache installed and
156 configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache
157 documentation for instructions.
159 Once you've got that set up, point Apache at your Django FastCGI instance by
160 editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two
161 things:
163     * Use the ``FastCGIExternalServer`` directive to specify the location of
164       your FastCGI server.
165     * Use ``mod_rewrite`` to point URLs at FastCGI as appropriate.
167 .. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
169 Specifying the location of the FastCGI server
170 ---------------------------------------------
172 The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI
173 server. As the `FastCGIExternalServer docs`_ explain, you can specify either a
174 ``socket`` or a ``host``. Here are examples of both::
176     # Connect to FastCGI via a socket / named pipe.
177     FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock
179     # Connect to FastCGI via a TCP host/port.
180     FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033
182 In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't
183 actually have to exist. It's just a URL used by the Web server internally -- a
184 hook for signifying which requests at a URL should be handled by FastCGI. (More
185 on this in the next section.)
187 .. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
189 Using mod_rewrite to point URLs at FastCGI
190 ------------------------------------------
192 The second step is telling Apache to use FastCGI for URLs that match a certain
193 pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to
194 ``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer``
195 directive, as explained in the previous section).
197 In this example, we tell Apache to use FastCGI to handle any request that
198 doesn't represent a file on the filesystem and doesn't start with ``/media/``.
199 This is probably the most common case, if you're using Django's admin site::
201     <VirtualHost 12.34.56.78>
202       ServerName example.com
203       DocumentRoot /home/user/public_html
204       Alias /media /home/user/python/django/contrib/admin/media
205       RewriteEngine On
206       RewriteRule ^/(media.*)$ /$1 [QSA,L,PT]
207       RewriteCond %{REQUEST_FILENAME} !-f
208       RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L]
209     </VirtualHost>
211 .. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
213 lighttpd setup
214 ==============
216 lighttpd is a lightweight Web server commonly used for serving static files. It
217 supports FastCGI natively and, thus, is a good choice for serving both static
218 and dynamic pages, if your site doesn't have any Apache-specific needs.
220 Make sure ``mod_fastcgi`` is in your modules list, somewhere after
221 ``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll
222 probably want ``mod_alias`` as well, for serving admin media.
224 Add the following to your lighttpd config file::
226     server.document-root = "/home/user/public_html"
227     fastcgi.server = (
228         "/mysite.fcgi" => (
229             "main" => (
230                 # Use host / port instead of socket for TCP fastcgi
231                 # "host" => "127.0.0.1",
232                 # "port" => 3033,
233                 "socket" => "/home/user/mysite.sock",
234                 "check-local" => "disable",
235             )
236         ),
237     )
238     alias.url = (
239         "/media/" => "/home/user/django/contrib/admin/media/",
240     )
242     url.rewrite-once = (
243         "^(/media.*)$" => "$1",
244         "^/favicon\.ico$" => "/media/favicon.ico",
245         "^(/.*)$" => "/mysite.fcgi$1",
246     )
248 Running multiple Django sites on one lighttpd
249 ---------------------------------------------
251 lighttpd lets you use "conditional configuration" to allow configuration to be
252 customized per host. To specify multiple FastCGI sites, just add a conditional
253 block around your FastCGI config for each site::
255     # If the hostname is 'www.example1.com'...
256     $HTTP["host"] == "www.example1.com" {
257         server.document-root = "/foo/site1"
258         fastcgi.server = (
259            ...
260         )
261         ...
262     }
264     # If the hostname is 'www.example2.com'...
265     $HTTP["host"] == "www.example2.com" {
266         server.document-root = "/foo/site2"
267         fastcgi.server = (
268            ...
269         )
270         ...
271     }
273 You can also run multiple Django installations on the same site simply by
274 specifying multiple entries in the ``fastcgi.server`` directive. Add one
275 FastCGI host for each.
277 Running Django on a shared-hosting provider with Apache
278 =======================================================
280 Many shared-hosting providers don't allow you to run your own server daemons or
281 edit the ``httpd.conf`` file. In these cases, it's still possible to run Django
282 using Web server-spawned processes.
284 .. admonition:: Note
286     If you're using Web server-spawned processes, as explained in this section,
287     there's no need for you to start the FastCGI server on your own. Apache
288     will spawn a number of processes, scaling as it needs to.
290 In your Web root directory, add this to a file named ``.htaccess`` ::
292     AddHandler fastcgi-script .fcgi
293     RewriteEngine On
294     RewriteCond %{REQUEST_FILENAME} !-f
295     RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
297 Then, create a small script that tells Apache how to spawn your FastCGI
298 program. Create a file ``mysite.fcgi`` and place it in your Web directory, and
299 be sure to make it executable::
301     #!/usr/bin/python
302     import sys, os
304     # Add a custom Python path.
305     sys.path.insert(0, "/home/user/python")
307     # Switch to the directory of your project. (Optional.)
308     # os.chdir("/home/user/myproject")
310     # Set the DJANGO_SETTINGS_MODULE environment variable.
311     os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
313     from django.core.servers.fastcgi import runfastcgi
314     runfastcgi(method="threaded", daemonize="false")
316 Restarting the spawned server
317 -----------------------------
319 If you change any Python code on your site, you'll need to tell FastCGI the
320 code has changed. But there's no need to restart Apache in this case. Rather,
321 just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the
322 file will change. When Apache sees the file has been updated, it will restart
323 your Django application for you.
325 If you have access to a command shell on a Unix system, you can accomplish this
326 easily by using the ``touch`` command::
328     touch mysite.fcgi
330 Serving admin media files
331 =========================
333 Regardless of the server and configuration you eventually decide to use, you will
334 also need to give some thought to how to serve the admin media files. The
335 advice given in the modpython_ documentation is also applicable in the setups
336 detailed above.
338 .. _modpython: ../modpython/#serving-the-admin-files