Apache module mod_fastcgi
This 3rd party module provides support for the FastCGI protocol. FastCGI is a language independent, scalable, open extension to CGI that provides high performance and persistence without the limitations of server specific APIs.
FastCGI applications are not limited to a particular development language (the protocol is open). FastCGI application libraries currently exist for Perl, C/C++, Java, Python, TCL, SmallEiffel, and Smalltalk.
FastCGI applications use TCP or Unix sockets to communicate with the web server. This scalable architecture allows applications to run on the same platform as the web server or on many machines scattered across an enterprise network.
FastCGI applications are portable to other web server platforms. FastCGI is supported either directly or through commercial extensions by most popular web servers.
FastCGI applications are fast because they're persistent. There is no per-request startup and initialization overhead. This makes possible the development of applications which would otherwise be impractical within the CGI paradigm (e.g. a huge Perl script, or an application which requires a connection to one or more databases).
See the FastCGI website for more information. To receive FastCGI related
announcements and notifications of software updates, send mail to fastcgi-announce-request@fastcgi.com with
"subscribe" in the Subject field. To participate in the discussion of mod_fastcgi
and
FastCGI application development, send mail to fastcgi-developers-request@fastcgi.com with
"subscribe" in the Subject field.
For information about building and installing the module, see the INSTALL document that came with the distribution.
FastCGI applications under mod_fastcgi
are defined as one of three types: static, dynamic, or
external. They're configured using the FastCgiServer, FastCgiConfig, and FastCgiExternalServer directives respectively. Any URI that Apache identifies as a FastCGI application and which
hasn't been explicitly configured using a FastCgiServer or FastCgiExternalServer directive is handled as a dynamic application (see the FastCgiConfig directive for more information).
FastCGI static and dynamic applications are spawned and managed by the FastCGI Process Manager, fcgi-pm. The process manager is spawned by Apache at server initialization. External applications are presumed to be started and managed independently.
Apache must be configured to identify requests for FastCGI URIs. mod_fastcgi
registers (with
Apache) a handler type of fastcgi-script
for this purpose.
To configure Apache to handle all files (within the scope of the directive) as FastCGI applications (e.g. for a fcgi-bin directory):
SetHandler fastcgi-script
To configure Apache to handle files (within the scope of the directive) with the specified extension(s) as FastCGI applications:
AddHandler fastcgi-script fcg fcgi fpl
Consult the Apache documentation for more information regarding these and other directives which affect
request handling (such as Action).
Dynamic FastCGI applications require the ExecCGI
option be enabled (see the Options
directive) in the
application's directory.
mod_fastcgi
logs FastCGI application error (stderr) output to the server log associated with the
request. Errors reported by the FastCGI process manager, fcgi-pm, are reported to the main server log
(typically, logs/error_log). Data written to stdout or stderr before entering the FastCGI accept loop
or via a mechanism that is not FastCGI protocol aware will also be directed to the main server log. If
Apache's LogLevel
is set to
info
additional informational messages are printed to the logs, these messages may be especially
helpful while debugging a configuration.
Under Unix, expect your FastCGI application to see SIGPIPE, SIGUSR1, and SIGTERM. The latest FastCGI C, C++ and Perl application library installs default handlers if none are installed by the application. If an http client aborts a request before it completes, mod_fastcgi does too - this results in a SIGPIPE to the FastCGI application. At a minimum, SIGPIPE should be ignored (applications spawned by mod_fastcgi have this setup automatically). Ideally, it should result in an early abort of the request handling within your application and a return to the top of the FastCGI accept() loop. Apache uses SIGUSR1 to request a "graceful" process restart/shutdown. It is sent to Apache's process group (which includes applications spawned by mod_fastcgi). Ideally, it should result in a FastCGI application finishing the current request, if any, and then an exit. The mod_fastcgi process manager isn't particularly patient though (there's room for improvement here) and since it has to shutdown too, sends a SIGTERM to all of the FastCGI applications it is responsible for. Apache will restart the process manager and it will restart its managed applications (as if the server was just started). SIGTERM is, well, SIGTERM - your application should exit quickly.
Under Windows, there are no signals. A shutdown event is used instead. This is setup by mod_fastcgi and honored by the latest version of the C, C++, and Perl application library. If your using a library which doesn't support this, your application will not get shutdown during an Apache restart/shutdown (there's room for improvement here).
To pass per-request environment variables to FastCGI applications, have a look at: mod_env
(SetEnv
,
PassEnv
, UnSetEnv
), mod_setenvif
(BrowserMatch
,
BrowserMatchNoCase
, SetEnvIf
, SetEnvIfNoCase
), and mod_rewrite
(if you're feeling
adventurous).
FastCGI application output is buffered by default. This is not the case for CGI scripts (under Apache 1.3). To
override the default behavior, use the -flush
option (not available for dynamic applications).
Non-parsed header (nph-) scripts will be rejected by mod_fastcgi simply as warning the behavior is different
(create a symbolic link to the script without the "nph-" prefix if this poses a problem).
Redirects are handled similarly to CGI. Location headers with values that begin with "/" are treated as internal-redirects; otherwise, they are treated as external redirects (302).
Session affinity (as well as distribution) should be achievable outside of mod_fastcgi
using mod_rewrite
. If you get this
working, please post the details to fastcgi-developers@fastcgi.com so they can be included here.
The FastCGI specification is not implemented in its entirety and I've deviated a bit as well resulting in some Apache specific features.
The file descriptors for stdout and stderr are left open. This is prohibited by the specification. I can't see any reason to require that they be closed, and leaving them open prevents FastCGI applications which were not completely ported to FastCGI from failing miserably. This does not mean the applications shouldn't be fixed such that this doesn't occur, but is invaluable when using a 3rd party library (without source code) which expects to be able to write to stderr. Anything written to stdout or stderr in this manner will be directed to the main server log.
The Filter and Log Roles are not supported. The Filter Role has little value in Apache until the output of one handler can be piped into another (Apache 2.0 is expected to support this). The Log Role has some value, but Apache's "piped logs" feature is similar (and is even more CPU friendly).
Multiplexed requests are not supported. This does NOT mean FastCGI applications can't be multithreaded. It means that each request requires its own independent connect()/accept(). The protocol supports the concept of a connection simultaneously shared by multiple requests.
The Authorizer Role has three variations corresponding to three specific Apache request handling phases:
Authentication, Authorization, and Access Control. mod_fastcgi
sets up the (Apache specific)
environment variable "FCGI_APACHE_ROLE" to indicate which Apache authorizer phase is being
performed.
Authorizers under mod_fastcgi
are sent nearly all of the standard environment variables typically
available to CGI/FastCGI request handlers including some explicitly precluded by the FastCGI specification
(for authorizers); I didn't see the point in leaving them out. All headers returned by a FastCGI
Authorizer in a successful response (Status: 200) are passed to sub-processes (CGI/FastCGI invocations) as
environment variables rather than just those prefixed by Variable-
as the FastCGI specification
calls for; I didn't see the point in leaving them out either. FastCGI specification compliant authorizer
behavior can be obtained by using the -compat
option to the Auth server directives.
Custom failure responses from FastCGI authorizer applications are not supported (speak up if you need this). See the ErrorDocument directive for a workaround (a CGI/FastCGI application can serve the error document).
FastCgiServer
FastCgiConfig
FastCgiExternalServer
FastCgiIpcDir
FastCgiWrapper
FastCgiAuthenticator
FastCgiAuthenticatorAuthoritative
FastCgiAuthorizer
FastCgiAuthorizerAuthoritative
FastCgiAccessChecker
FastCgiAccessCheckerAuthoritative
Syntax: |
FastCgiServer filename [option ...]
|
Context: | server config |
The FastCgiServer
directive defines filename as a static FastCGI application. If the
filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
By default, the Process Manager will start one instance of the application with the default configuration
specified (in parentheses) below. Should a static application instance die for any reason
mod_fastcgi
will spawn another to replace it and log the event (at the warn
LogLevel
).
Option can be one of (case insensitive):
-appConnTimeout n (0 seconds)
connect()
should be used. Blocking connect()
s have an OS
dependent internal timeout.
If the timeout expires, a SERVER_ERROR results. For non-zero
values, this is the amount of time used in a select()
to write to the file descriptor returned
by a non-blocking connect().
Non-blocking connect()
s are troublesome on many
platforms. See also -idle-timeout
, it produces similar results but in a more portable
manner.-port
option and dynamic applications) use this value
successfully to limit the amount of time to wait for a connection (i.e. it's not
"troublesome"). By default, this is 90 seconds (FCGI_NAMED_PIPE_CONNECT_TIMEOUT in
mod_fastcgi.h).
-idle-timeout n (30 seconds)
error
LogLevel
). The inactivity timer
applies only as long as a connection is pending with the FastCGI application. If a request is queued to an
application, but the application doesn't respond (by writing and flushing) within this period, the
request will be aborted. If communication is complete with the application but incomplete with the client
(the response is buffered), the timeout does not apply.
-initial-env name[=[value]] (none)
-init-start-delay n (1 second)
-flush (none)
mod_fastcgi
buffers data in order to free the application as quickly as possible.
-listen-queue-depth n (100)
listen()
queue (also known as the backlog) shared by all of the instances of this
application. A deeper listen queue allows the server to cope with transient load fluctuations without
rejecting requests; it does not increase throughput. Adding additional application instances may increase
throughput/performance, depending upon the application and the host.
-pass-header header (none)
-port n (none)
-socket
and -port
options are mutually exclusive.
-priority n (0)
setpriority()
).
-processes n (1)
-restart-delay n (5 seconds)
-socket filename (generated)
FastCgiIpcDir
. This option makes the application accessible to other
applications (e.g. cgi-fcgi
) on the same machine or via an external FastCGI application
definition (FastCgiExternalServer
). If neither the
-socket
nor the -port
options are given, the module generates a Unix domain
socket filename. The -socket
and -port
options are mutually exclusive.
FastCgiIpcDir
. This option makes the application accessible to other
applications (e.g. cgi-fcgi
) on the same machine or via an external FastCGI application
definition (FastCgiExternalServer
). If neither the
-socket
nor the -port
options are given, the module generates a name for the
named pipe. The -socket
and -port
options are mutually exclusive.
Syntax: |
FastCgiConfig option [option ...]
|
Context: | server config |
The FastCgiConfig
directive defines the default parameters for all dynamic FastCGI
applications. This directive does not affect static or external applications in any way.
Dynamic applications are not started at server initialization, but upon demand. If the demand is heavy, additional application instances are started. As the demand fades, application instances are killed off. Many of the options govern this process.
Option can be one of (case insensitive):
-appConnTimeout n (0 seconds)
connect()
should be used. Blocking connect()
s have an OS
dependent internal timeout. If the timeout expires, a SERVER_ERROR results. For non-zero values, this is
the amount of time used in a select()
to write to the file descriptor returned by a
non-blocking connect()
. Non-blocking connect()
s are troublesome on many
platforms. See also -idle-timeout
, it produces similar results but in a more portable
manner.-port
option and dynamic applications) use this value
successfully to limit the amount of time to wait for a connection (i.e. it's not
"troublesome"). By default, this is 90 seconds (FCGI_NAMED_PIPE_CONNECT_TIMEOUT in
mod_fastcgi.h).
-autoUpdate (none)
-restart
.
-flush (none)
mod_fastcgi
buffers data in order to free the application as quickly as possible.
-gainValue n (0.5)
1 - gainValue
), so making it smaller weights old values more than the current
value (which is scaled by gainValue
).
-idle-timeout n (30 seconds)
error
LogLevel
). The inactivity timer
applies only as long as a connection is pending with the FastCGI application. If a request is queued to an
application, but the application doesn't respond (by writing and flushing) within this period, the
request will be aborted. If communication is complete with the application but incomplete with the client
(the response is buffered), the timeout does not apply.
-initial-env name[=[value]] (none)
-init-start-delay n (1 second)
-killInterval n (300 seconds)
-listen-queue-depth n (100)
listen()
queue (also known as the backlog) shared by all instances of
applications. A deeper listen queue allows the server to cope with transient load fluctuations without
rejecting requests; it does not increase throughput. Adding additional application instances may increase
throughput/performance, depending upon the application and the host.
-maxClassProcesses n (10)
-maxProcesses n (50)
-minProcesses n (5)
-multiThreshold n (50)
singleThreshold
is used instead.multiThreshhold
is also accepted.
-pass-header header (none)
-priority n (0)
setpriority()
).
-processSlack n (5)
processSlack
exceeds maxProcesses
, the process manager invokes the killing
policy. This is to improve performance at higher loads by killing some of the most inactive application
instances before reaching maxProcesses
.
-restart (none)
-restart-delay n (5 seconds)
-singleThreshold n (0)
-appConnTimeout
is set).singleThreshhold
is also accepted.
-startDelay n (3 seconds)
startDelay
must be less than appConnTimeout
to
be effective.
-updateInterval n (300 seconds)
Syntax: |
FastCgiExternalServer filename -host hostname:port [option ...]
|
FastCgiExternalServer filename -socket filename [option ...]
|
|
Context: | server config |
The FastCgiExternalServer
directive defines filename as an external FastCGI application.
If filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot. The filename does not have to
exist in the local filesystem. URIs that Apache resolves to this filename will be handled by this
external FastCGI application..
External FastCGI applications are not started by the process manager, they are presumed to be started and
managed "external" to Apache and mod_fastcgi. The FastCGI devkit provides a simple tool,
cgi-fcgi
, for starting FastCGI applications independent of the server (applications can also be
self-starting, see the devkit).
Option can be one of (case insensitive):
-appConnTimeout n (0 seconds)
connect()
should be used. Blocking connect()
s have an OS
dependent internal timeout. If the timeout expires, a SERVER_ERROR results. For non-zero values, this is
the amount of time used in a select()
to write to the file descriptor returned by a
non-blocking connect()
. Non-blocking connect()
s are troublesome on many
platforms. See also -idle-timeout
, it produces similar results but in a more portable
manner.-port
option and dynamic applications) use this value
successfully to limit the amount of time to wait for a connection (i.e. it's not
"troublesome"). By default, this is 90 seconds (FCGI_NAMED_PIPE_CONNECT_TIMEOUT in
mod_fastcgi.h).
-idle-timeout n (30 seconds)
error
LogLevel
). The inactivity timer
applies only as long as a connection is pending with the FastCGI application. If a request is queued to an
application, but the application doesn't respond (by writing and flushing) within this period, the
request will be aborted. If communication is complete with the application but incomplete with the client
(the response is buffered), the timeout does not apply.
-flush (none)
mod_fastcgi
buffers data in order to free the application as quickly as possible.
-host hostname:port (none)
-socket
and -host
options are mutually exclusive.
-pass-header header (none)
-socket filename (none)
FastCgiIpcDir
. The
-socket
and -port
options are mutually exclusive.
FastCgiIpcDir
. The
-socket
and -port
options are mutually exclusive.
Syntax: |
Unix: FastCgiIpcDir directory
|
Windows NT: FastCgiIpcDir name
|
|
Default: |
Unix: FastCgiIpcDir /tmp/fcgi
|
Windows NT: FastCgiIpcDir \\.\pipe\ModFastCgi\
|
|
Context: | server config |
Unix: The FastCgiIpcDir
directive specifies directory as the place to store
(and in the case of external FastCGI applications, find) the Unix socket files used for communication between
the applications and the web server. If the directory does not begin with a slash (/) then it is assumed to be
relative to the ServerRoot. If the
directory doesn't exist, an attempt is made to create it with appropriate permissions. Do not specify a
directory that is not on a local filesystem! If you use the default directory (or another directory within
/tmp
), mod_fastcgi
will break if your system periodically deletes files from
/tmp
.
Windows NT: The FastCgiIpcDir
directive specifies name as the root for the
named pipes used for communication between the application and the web server. The name must be in the
form of \\.\pipe\pipename. The pipename part can contain any character other than a
backslash
The FastCgiIpcDir
directive must precede any FastCgiServer
or FastCgiExternalServer
directives (which make use of Unix sockets).
The directory must be readable, writeable, and executable (searchable) by the web server, but otherwise should
not be accessible to anyone.
Syntax: |
FastCgiWrapper On | Off | filename
|
Default: |
FastCgiWrapper Off
|
Context: | server config |
The FastCgiWrapper
directive is used to enable support for a wrapper such as suexec (included with Apache in the support directory) or cgiwrap. To use the same wrapper used by Apache, set
FastCgiWrapper
to On (NOTE - mod_fastcgi cannot reliably determine the wrapper used by
Apache when built as a DSO). The On argument requires suexec be enabled in Apache (for CGI). To use a
specific wrapper, specify a filename. If the filename does not begin with a slash (/) then it is
assumed to be relative to the ServerRoot.
The wrapper is used to invoke all FastCGI applications (in the future this directive will have directory
context).
When FastCgiWrapper
is enabled, no assumptions are made about the target application and thus
presence and permissions checks cannot be made. This is the responsibility of the wrapper.
The wrapper is invoked with the following arguments: username, group, application. The username and group are determined as described below. The application is the "filename" Apache resolves the requested URI to (dynamic) or the filename provided as an argument to another FastCGI (server or authorizer) directive. These arguments may or may not be used by the wrapper (e.g. suexec uses them, cgiwrap parses the URI and ignores them). The environment passed to the wrapper is identical to the environment passed when a wrapper is not in use.
When FastCgiWrapper
is enabled, the location of static or external FastCGI application directives
can be important. They inherit their user and group from the User
and Group
of the
virtual server in which they were defined. User
and Group
directives should precede
FastCGI application definitions. Note that this does not limit the FastCGI application to the virtual
server in which they were defined, the application is allowed to service requests from any virtual server with
the same user and group. If a request is received for a FastCGI application without an existing matching
definition running with the correct user and group, a dynamic instance of the application is started with the
correct user and group. This can lead to multiple copies of the same application running with different
user/group. If this is a problem, preclude navigation to the application from other virtual servers or
configure the virtual servers with the same User and Group.
See the Apache documentation for more information about suexec (make sure you fully understand the security implications).
Syntax: |
FastCgiAuthenticator filename [-compat]
|
Context: | directory |
The FastCgiAuthenticator
directive is used to define a FastCGI application as a per-directory
authenticator. Authenticators verify the requestor is who he says he is by matching the provided username and
password against a list or database of known users and passwords. FastCGI based authenticators are useful
primarily when the user database is maintained within an existing independent program or resides on a machine
other than the web server.
If the FastCGI application filename does not have a corresponding static or external server definition, it is started as a dynamic FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
FastCgiAuthenticator
is used within Directory
or Location
containers and must include an
AuthType
and AuthName
directive. Only the
Basic
user authentication type is supported. It must be accompanied by a require
or FastCgiAuthorizer
directive in order to work correctly.
<Directory htdocs/protected> AuthType Basic AuthName ProtectedRealm FastCgiAuthenticator fcgi-bin/authenticator require valid-user </Directory>
mod_fastcgi
sends nearly all of the standard environment variables typically available to
CGI/FastCGI request handlers. All headers returned by a FastCGI authentication application in a successful
response (Status: 200) are passed to sub-processes (CGI/FastCGI invocations) as environment variables. All
headers returned in an unsuccessful response are passed on to the client. FastCGI specification compliant
behavior can be obtained by using the -compat
option.
mod_fastcgi
sets the environment variable "FCGI_APACHE_ROLE" to
"AUTHENTICATOR" to indicate which (Apache specific) authorizer phase is being performed.
Custom failure responses from FastCGI authorizer applications are not (yet?) supported. See the ErrorDocument directive for a workaround (a FastCGI application can serve the document).
Syntax: |
FastCgiAuthenticatorAuthoritative On | Off
|
Default: |
FastCgiAuthenticatorAuthoritative On
|
Context: | directory |
Setting the FastCgiAuthenticatorAuthoritative
directive explicitly to Off allows
authentication to be passed on to lower level modules (as defined in the Configuration
and
modules.c
files) if the FastCGI application fails to authenticate the user.
A common use for this is in conjunction with a well protected AuthUserFile
containing a few
(administration related) users.
By default, control is not passed on and an unknown user will result in an Authorization Required reply. Disabling the default should be carefully considered.
Syntax: |
FastCgiAuthorizer filename [-compat]
|
Context: | directory |
The FastCgiAuthorizer
directive is used to define a FastCGI application as a per-directory
authorizer. Authorizers validate whether an authenticated requestor is allowed access to the requested
resource. FastCGI based authorizers are useful primarily when there is a dynamic component to the
authorization decision such as a time of day or whether or not the user has paid his bills.
If the FastCGI application filename does not have a corresponding static or external server definition, it is started as a dynamic FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
FastCgiAuthorizer
is used within Directory
or Location
containers and must include an
AuthType
and AuthName
directive. It must be
accompanied by an authentication directive such as FastCgiAuthenticator
, AuthUserFile
, AuthDBUserFile
or AuthDBMUserFile
in order
to work correctly.
<Directory htdocs/protected> AuthType Basic AuthName ProtectedRealm AuthDBMUserFile conf/authentication-database FastCgiAuthorizer fcgi-bin/authorizer </Directory>
mod_fastcgi
sends nearly all of the standard environment variables typically available to
CGI/FastCGI request handlers. All headers returned by a FastCGI authorizer application in a successful
response (Status: 200) are passed to sub-processes (CGI/FastCGI invocations) as environment variables. All
headers returned in an unsuccessful response are passed on to the client. FastCGI specification compliant
behavior can be obtained by using the -compat
option.
mod_fastcgi
sets the environment variable "FCGI_APACHE_ROLE" to "AUTHORIZER"
to indicate which (Apache specific) authorizer phase is being performed.
Custom failure responses from FastCGI authorizer applications are not (yet?) supported. See the ErrorDocument directive for a workaround (a FastCGI application can serve the document).
Syntax: |
FastCgiAuthorizerAuthoritative On | Off
|
Default: |
FastCgiAuthorizerAuthoritative On
|
Context: | directory |
Setting the FastCgiAuthorizerAuthoritative
directive explicitly to Off allows
authorization to be passed on to lower level modules (as defined in the Configuration
and
modules.c
files) if the FastCGI application fails to authorize the user.
By default, control is not passed on and an unauthorized user will result in an Authorization Required reply. Disabling the default should be carefully considered.
Syntax: |
FastCgiAccessChecker filename [-compat]
|
Context: | directory |
The FastCgiAccessChecker
(suggestions for a better name are welcome) directive is used to define
a FastCGI application as a per-directory access validator. The Apache Access phase precede user authentication
and thus the decision to (dis)allow access to the requested resource is based on the HTTP headers submitted
with the request. FastCGI based authorizers are useful primarily when there is a dynamic component to the
access validation decision such as a time of day or whether or not a domain has paid his bills.
If the FastCGI application filename does not have a corresponding static or external server definition, it is started as a dynamic FastCGI application. If the filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
FastCgiAccessChecker
is used within Directory
or Location
containers.
<Directory htdocs/protected> FastCgiAccessChecker fcgi-bin/access-checker </Directory>
mod_fastcgi
sends nearly all of the standard environment variables typically available to
CGI/FastCGI request handlers. All headers returned by a FastCGI access-checker application in a successful
response (Status: 200) are passed to sub-processes (CGI/FastCGI invocations) as environment variables. All
headers returned in an unsuccessful response are passed on to the client. FastCGI specification compliant
behavior can be obtained by using the -compat
option.
mod_fastcgi
sets the environment variable "FCGI_APACHE_ROLE" to
"ACCESS_CHECKER" to indicate which (Apache specific) authorizer phase is being performed.
Custom failure responses from FastCGI authorizer applications are not (yet?) supported. See the ErrorDocument directive for a workaround (a FastCGI application can serve the document).
Syntax: |
FastCgiAccessCheckerAuthoritative On | Off
|
Default: |
FastCgiAccessCheckerAuthoritative On
|
Context: | directory |
Setting the FastCgiAccessCheckerAuthoritative
directive explicitly to Off allows access
checking to be passed on to lower level modules (as defined in the Configuration
and
modules.c
files) if the FastCGI application fails to allow access.
By default, control is not passed on and a failed access check will result in a Forbidden reply. Disabling the default should be carefully considered.