fastcgi.txt 16 KB

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