fastcgi.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. ============================================
  2. How to use Django with FastCGI, SCGI, or AJP
  3. ============================================
  4. .. highlight:: bash
  5. Although the current preferred setup for running Django is :doc:`Apache with
  6. mod_wsgi </howto/deployment/modwsgi>`, many people use shared hosting, on
  7. which protocols such as FastCGI, SCGI or AJP are the only viable options. In
  8. some setups, these protocols may provide better performance than mod_wsgi_.
  9. .. admonition:: Note
  10. This document primarily focuses on FastCGI. Other protocols, such as SCGI
  11. and AJP, are also supported, through the ``flup`` Python package. See the
  12. Protocols_ section below for specifics about SCGI and AJP.
  13. Essentially, FastCGI is an efficient way of letting an external application
  14. serve pages to a Web server. The Web server delegates the incoming Web requests
  15. (via a socket) to FastCGI, which executes the code and passes the response back
  16. to the Web server, which, in turn, passes it back to the client's Web browser.
  17. Like mod_python, FastCGI allows code to stay in memory, allowing requests to be
  18. served with no startup time. Unlike mod_python_ (or `mod_perl`_), a FastCGI
  19. process doesn't run inside the Web server process, but in a separate,
  20. persistent process.
  21. .. _mod_wsgi: http://code.google.com/p/modwsgi/
  22. .. _mod_perl: http://perl.apache.org/
  23. .. _mod_python: http://www.modpython.org/
  24. .. admonition:: Why run code in a separate process?
  25. The traditional ``mod_*`` arrangements in Apache embed various scripting
  26. languages (most notably PHP, Python and Perl) inside the process space of
  27. your Web server. Although this lowers startup time -- because code doesn't
  28. have to be read off disk for every request -- it comes at the cost of
  29. memory use. For mod_python, for example, every Apache process gets its own
  30. Python interpreter, which uses up a considerable amount of RAM.
  31. Due to the nature of FastCGI, it's even possible to have processes that run
  32. under a different user account than the Web server process. That's a nice
  33. security benefit on shared systems, because it means you can secure your
  34. code from other users.
  35. Prerequisite: flup
  36. ==================
  37. Before you can start using FastCGI with Django, you'll need to install flup_, a
  38. Python library for dealing with FastCGI. Version 0.5 or newer should work fine.
  39. .. _flup: http://www.saddi.com/software/flup/
  40. Starting your FastCGI server
  41. ============================
  42. FastCGI operates on a client-server model, and in most cases you'll be starting
  43. the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or
  44. otherwise) only contacts your Django-FastCGI process when the server needs a
  45. dynamic page to be loaded. Because the daemon is already running with the code
  46. in memory, it's able to serve the response very quickly.
  47. .. admonition:: Note
  48. If you're on a shared hosting system, you'll probably be forced to use
  49. Web server-managed FastCGI processes. See the section below on running
  50. Django with Web server-managed processes for more information.
  51. A Web server can connect to a FastCGI server in one of two ways: It can use
  52. either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a
  53. TCP socket. What you choose is a manner of preference; a TCP socket is usually
  54. easier due to permissions issues.
  55. To start your server, first change into the directory of your project (wherever
  56. your :doc:`manage.py </ref/django-admin>` is), and then run the
  57. :djadmin:`runfcgi` command::
  58. ./manage.py runfcgi [options]
  59. If you specify ``help`` as the only option after :djadmin:`runfcgi`, it'll
  60. display a list of all the available options.
  61. You'll need to specify either a ``socket``, a ``protocol`` or both ``host`` and
  62. ``port``. Then, when you set up your Web server, you'll just need to point it at
  63. the host/port or socket you specified when starting the FastCGI server. See the
  64. examples_, below.
  65. Protocols
  66. ---------
  67. Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and
  68. `AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred
  69. protocol by using the ``protocol=<protocol_name>`` option with ``./manage.py
  70. runfcgi`` -- where ``<protocol_name>`` may be one of: ``fcgi`` (the default),
  71. ``scgi`` or ``ajp``. For example::
  72. ./manage.py runfcgi protocol=scgi
  73. .. _flup: http://www.saddi.com/software/flup/
  74. .. _fastcgi: http://www.fastcgi.com/
  75. .. _SCGI: http://python.ca/scgi/protocol.txt
  76. .. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
  77. Examples
  78. --------
  79. Running a threaded server on a TCP port::
  80. ./manage.py runfcgi method=threaded host=127.0.0.1 port=3033
  81. Running a preforked server on a Unix domain socket::
  82. ./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
  83. Run without daemonizing (backgrounding) the process (good for debugging)::
  84. ./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock maxrequests=1
  85. Stopping the FastCGI daemon
  86. ---------------------------
  87. If you have the process running in the foreground, it's easy enough to stop it:
  88. Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when
  89. you're dealing with background processes, you'll need to resort to the Unix
  90. ``kill`` command.
  91. If you specify the ``pidfile`` option to :djadmin:`runfcgi`, you can kill the
  92. running FastCGI daemon like this::
  93. kill `cat $PIDFILE`
  94. ...where ``$PIDFILE`` is the ``pidfile`` you specified.
  95. To easily restart your FastCGI daemon on Unix, try this small shell script::
  96. #!/bin/bash
  97. # Replace these three settings.
  98. PROJDIR="/home/user/myproject"
  99. PIDFILE="$PROJDIR/mysite.pid"
  100. SOCKET="$PROJDIR/mysite.sock"
  101. cd $PROJDIR
  102. if [ -f $PIDFILE ]; then
  103. kill `cat -- $PIDFILE`
  104. rm -f -- $PIDFILE
  105. fi
  106. exec /usr/bin/env - \
  107. PYTHONPATH="../python:.." \
  108. ./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE
  109. Apache setup
  110. ============
  111. To use Django with Apache and FastCGI, you'll need Apache installed and
  112. configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache
  113. documentation for instructions.
  114. Once you've got that set up, point Apache at your Django FastCGI instance by
  115. editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two
  116. things:
  117. * Use the ``FastCGIExternalServer`` directive to specify the location of
  118. your FastCGI server.
  119. * Use ``mod_rewrite`` to point URLs at FastCGI as appropriate.
  120. .. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
  121. Specifying the location of the FastCGI server
  122. ---------------------------------------------
  123. The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI
  124. server. As the `FastCGIExternalServer docs`_ explain, you can specify either a
  125. ``socket`` or a ``host``. Here are examples of both:
  126. .. code-block:: apache
  127. # Connect to FastCGI via a socket / named pipe.
  128. FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock
  129. # Connect to FastCGI via a TCP host/port.
  130. FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033
  131. In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't
  132. actually have to exist. It's just a URL used by the Web server internally -- a
  133. hook for signifying which requests at a URL should be handled by FastCGI. (More
  134. on this in the next section.)
  135. .. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
  136. Using mod_rewrite to point URLs at FastCGI
  137. ------------------------------------------
  138. The second step is telling Apache to use FastCGI for URLs that match a certain
  139. pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to
  140. ``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer``
  141. directive, as explained in the previous section).
  142. In this example, we tell Apache to use FastCGI to handle any request that
  143. doesn't represent a file on the filesystem and doesn't start with ``/media/``.
  144. This is probably the most common case, if you're using Django's admin site:
  145. .. code-block:: apache
  146. <VirtualHost 12.34.56.78>
  147. ServerName example.com
  148. DocumentRoot /home/user/public_html
  149. Alias /media /home/user/python/django/contrib/admin/media
  150. RewriteEngine On
  151. RewriteRule ^/(media.*)$ /$1 [QSA,L,PT]
  152. RewriteCond %{REQUEST_FILENAME} !-f
  153. RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L]
  154. </VirtualHost>
  155. .. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
  156. Django will automatically use the pre-rewrite version of the URL when
  157. constructing URLs with the ``{% url %}`` template tag (and similar methods).
  158. lighttpd setup
  159. ==============
  160. lighttpd_ is a lightweight Web server commonly used for serving static files. It
  161. supports FastCGI natively and, thus, is a good choice for serving both static
  162. and dynamic pages, if your site doesn't have any Apache-specific needs.
  163. .. _lighttpd: http://www.lighttpd.net/
  164. Make sure ``mod_fastcgi`` is in your modules list, somewhere after
  165. ``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll
  166. probably want ``mod_alias`` as well, for serving admin media.
  167. Add the following to your lighttpd config file:
  168. .. code-block:: lua
  169. server.document-root = "/home/user/public_html"
  170. fastcgi.server = (
  171. "/mysite.fcgi" => (
  172. "main" => (
  173. # Use host / port instead of socket for TCP fastcgi
  174. # "host" => "127.0.0.1",
  175. # "port" => 3033,
  176. "socket" => "/home/user/mysite.sock",
  177. "check-local" => "disable",
  178. )
  179. ),
  180. )
  181. alias.url = (
  182. "/media" => "/home/user/django/contrib/admin/media/",
  183. )
  184. url.rewrite-once = (
  185. "^(/media.*)$" => "$1",
  186. "^/favicon\.ico$" => "/media/favicon.ico",
  187. "^(/.*)$" => "/mysite.fcgi$1",
  188. )
  189. Running multiple Django sites on one lighttpd
  190. ---------------------------------------------
  191. lighttpd lets you use "conditional configuration" to allow configuration to be
  192. customized per host. To specify multiple FastCGI sites, just add a conditional
  193. block around your FastCGI config for each site::
  194. # If the hostname is 'www.example1.com'...
  195. $HTTP["host"] == "www.example1.com" {
  196. server.document-root = "/foo/site1"
  197. fastcgi.server = (
  198. ...
  199. )
  200. ...
  201. }
  202. # If the hostname is 'www.example2.com'...
  203. $HTTP["host"] == "www.example2.com" {
  204. server.document-root = "/foo/site2"
  205. fastcgi.server = (
  206. ...
  207. )
  208. ...
  209. }
  210. You can also run multiple Django installations on the same site simply by
  211. specifying multiple entries in the ``fastcgi.server`` directive. Add one
  212. FastCGI host for each.
  213. Cherokee setup
  214. ==============
  215. Cherokee is a very fast, flexible and easy to configure Web Server. It
  216. supports the widespread technologies nowadays: FastCGI, SCGI, PHP, CGI, SSI,
  217. TLS and SSL encrypted connections, Virtual hosts, Authentication, on the fly
  218. encoding, Load Balancing, Apache compatible log files, Data Base Balancer,
  219. Reverse HTTP Proxy and much more.
  220. The Cherokee project provides a documentation to `setting up Django`_ with Cherokee.
  221. .. _setting up Django: http://www.cherokee-project.com/doc/cookbook_django.html
  222. Running Django on a shared-hosting provider with Apache
  223. =======================================================
  224. Many shared-hosting providers don't allow you to run your own server daemons or
  225. edit the ``httpd.conf`` file. In these cases, it's still possible to run Django
  226. using Web server-spawned processes.
  227. .. admonition:: Note
  228. If you're using Web server-spawned processes, as explained in this section,
  229. there's no need for you to start the FastCGI server on your own. Apache
  230. will spawn a number of processes, scaling as it needs to.
  231. In your Web root directory, add this to a file named ``.htaccess``:
  232. .. code-block:: apache
  233. AddHandler fastcgi-script .fcgi
  234. RewriteEngine On
  235. RewriteCond %{REQUEST_FILENAME} !-f
  236. RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
  237. Then, create a small script that tells Apache how to spawn your FastCGI
  238. program. Create a file ``mysite.fcgi`` and place it in your Web directory, and
  239. be sure to make it executable:
  240. .. code-block:: python
  241. #!/usr/bin/python
  242. import sys, os
  243. # Add a custom Python path.
  244. sys.path.insert(0, "/home/user/python")
  245. # Switch to the directory of your project. (Optional.)
  246. # os.chdir("/home/user/myproject")
  247. # Set the DJANGO_SETTINGS_MODULE environment variable.
  248. os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
  249. from django.core.servers.fastcgi import runfastcgi
  250. runfastcgi(method="threaded", daemonize="false")
  251. Restarting the spawned server
  252. -----------------------------
  253. If you change any Python code on your site, you'll need to tell FastCGI the
  254. code has changed. But there's no need to restart Apache in this case. Rather,
  255. just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the
  256. file will change. When Apache sees the file has been updated, it will restart
  257. your Django application for you.
  258. If you have access to a command shell on a Unix system, you can accomplish this
  259. easily by using the ``touch`` command::
  260. touch mysite.fcgi
  261. Serving admin media files
  262. =========================
  263. Regardless of the server and configuration you eventually decide to use, you
  264. will also need to give some thought to how to serve the admin media files. The
  265. advice given in the :ref:`modpython <serving-the-admin-files>` documentation
  266. is also applicable in the setups detailed above.
  267. Forcing the URL prefix to a particular value
  268. ============================================
  269. Because many of these fastcgi-based solutions require rewriting the URL at
  270. some point inside the webserver, the path information that Django sees may not
  271. resemble the original URL that was passed in. This is a problem if the Django
  272. application is being served from under a particular prefix and you want your
  273. URLs from the ``{% url %}`` tag to look like the prefix, rather than the
  274. rewritten version, which might contain, for example, ``mysite.fcgi``.
  275. Django makes a good attempt to work out what the real script name prefix
  276. should be. In particular, if the webserver sets the ``SCRIPT_URL`` (specific
  277. to Apache's mod_rewrite), or ``REDIRECT_URL`` (set by a few servers, including
  278. Apache + mod_rewrite in some situations), Django will work out the original
  279. prefix automatically.
  280. In the cases where Django cannot work out the prefix correctly and where you
  281. want the original value to be used in URLs, you can set the
  282. ``FORCE_SCRIPT_NAME`` setting in your main ``settings`` file. This sets the
  283. script name uniformly for every URL served via that settings file. Thus you'll
  284. need to use different settings files if you want different sets of URLs to
  285. have different script names in this case, but that is a rare situation.
  286. As an example of how to use it, if your Django configuration is serving all of
  287. the URLs under ``'/'`` and you wanted to use this setting, you would set
  288. ``FORCE_SCRIPT_NAME = ''`` in your settings file.