FastCGI on DreamHost
- FAQ - Frequently asked questions, examples and explanations.
- FastCGI White Paper - Describes the motivation for FastCGI, the FastCGI interface, FastCGI application roles, the FastCGI application library, and FastCGI performance.
- Understanding FastCGI Application Performance - Why FastCGI applications often run faster than applications coded directly to Web server APIs.
- FastCGI Developer's Kit - How to configure and build the kit, and write applications using the FastCGI application libraries.
- FastCGI Programmer's Guide - Programmer-oriented documentation for developers of FastCGI applications. The content overlaps considerably with the Developer's Kit document.
- FastCGI Specification - Defines the interface between a FastCGI application and the Web server.
- FastCGI - A High-Performance Gateway Interface - Position paper presented at the workshop "Programming the Web -- a search for APIs", Fifth International World Wide Web Conference, 6 May 1996, Paris, France.
- Rob's Open Source '99 Presentations - Two FastCGI related presentations given at O'reilly's Open Source '99 Conference in Monterey, CA.
- The Apache FastCGI Process Manager - A description of some of the functionality of the process manager in mod_fastcgi. I'm not sure how accurate it is.
FastCGI configuration at Dreamhost:
FastCgiConfig -autoUpdate -initial-env RAILS_ENV=production -idle-timeout 120 -maxClassProcesses 5 -killInterval 300
Do not use custom php.ini with fast-cgi on dreamhost!
Setting up Apache to use PHP is similar to the normal configuration. Simply add the following lines to your httpd.conf, either in a VirtualHost directive, or in the main context
AddHandler php-fastcgi .php Action php-fastcgi /cgi-bin/php DirectoryIndex index.html index.shtml index.cgi index.php AddType application/x-httpd-php .php
Finally, copy or hard link your PHP binary from wherever you installed it to /export/httpd/cgi-bin/php. Now there is something there to run. These lines set up the Web server to pass requests for things of type .php to your FastCgiServer for processing. It also enables index.php as a directory index.
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, subscribe to fastcgi-announce. To participate in the discussion of mod_fastcgi and FastCGI application development, subscribe to fastcgi-developers. Summary 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-scriptTo configure Apache to handle files (within the scope of the directive) with the specified extension(s) as FastCGI applications:
AddHandler fastcgi-script fcg fcgi fplConsult 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. Notes 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. FastCGI Specification Compliance 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). The FastCGI protocol supports a feature, described in the specificiation as "multiplexing", that allows a single client-server connection to be simultaneously shared by multiple requests. This is not supported. This does *not* prevent FastCGI applications from supporting multiple simultaneous requests over independent connections. Of course, the application has to be specifically designed to do so by using a threaded or select/poll based server model. 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). Directives
- FastCgiServer
- FastCgiConfig<
- FastCgiExternalServer
- FastCgiIpcDir
- FastCgiWrapper
- FastCgiAuthenticator
- FastCgiAuthenticatorAuthoritative
- FastCgiAuthorizer
- FastCgiAuthorizerAuthoritative
- FastCgiAccessChecker
- FastCgiAccessCheckerAuthoritative
FastCgiServer Syntax: FastCgiServer filename [option ...] Context: server configThe 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) Unix: The number of seconds to wait for a connection to the FastCGI application to complete or 0 to indicate a blocking 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. Windows NT: TCP based applications work as above. Named pipe based applications (static applications configured without the -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). -group groupname|#gid (none) Unix (only): When FastCgiWrapper is in use, the group is used to invoke the wrapper. The -group option must be used together with -user. -idle-timeout n (30 seconds) The number of seconds of FastCGI application inactivity allowed before the request is aborted and the event is logged (at the 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) A name-value pair to be passed in the FastCGI application's initial environment. To pass a variable from Apache's environment, don't provide the "=" (if the variable isn't actually in the environment, it will be defined without a value). To define a variable without a value, provide the "=" without any value. The option can be used repeatedly. -init-start-delay n (1 second) The minimum number of seconds between the spawning of instances of this application. This delay decreases the demand placed on the system at server initialization. -flush (none) Force a write to the client as data is received from the application. By default, mod_fastcgi buffers data in order to free the application as quickly as possible. -listen-queue-depth n (100) The depth of 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) The name of an HTTP Request Header to be passed in the request environment. This option makes available the contents of headers which are normally not available (e.g. Authorization) to a CGI environment. -port n (none) The TCP port number (1-65535) the application will use for communication with the web server. This option makes the application accessible from other machines on the network (as well as this one). The -socket and -port options are mutually exclusive. -priority n (0) The process priority to be assigned to the application instances (using setpriority()). -processes n (1) The number of instances of the application to spawn at server initialization. -restart-delay n (5 seconds) The minimum number of seconds between the respawning of failed instances of this application. This delay prevents a broken application from soaking up too much of the system. -socket filename (generated) Unix: The filename of the Unix domain socket that the application will use for communication with the web server. The module creates the socket within the directory specified by 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. Windows NT: The name of the named pipe that the application will use for communication with the web server. The module creates the named pipe under the named pipe root specified by 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. -user username|#uid (none) Unix (only): When FastCgiWrapper is in use, the user is used to invoke the wrapper. The -user option must be used together with -group.
FastCgiConfig Syntax: FastCgiConfig option [option ...] Context: server configThe 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) Unix: The number of seconds to wait for a connection to the FastCGI application to complete or 0 to indicate a blocking 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. Windows NT: TCP based applications work as above. Named pipe based applications (static applications configured without the -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) Causes mod_fastcgi to check the modification time of the application on disk before processing each request. If the application on disk has been changed, the process manager is notified and all running instances of the application are killed off. In general, it's preferred that this type of functionality be built-in to the application (e.g. every 100th request it checks to see if there's a newer version on disk and exits if so). There may be an outstanding problem (bug) when this option is used with -restart. -flush (none) Force a write to the client as data is received from the application. By default, mod_fastcgi buffers data in order to free the application as quickly as possible. -gainValue n (0.5) A floating point value between 0 and 1 used as an exponent in the computation of the exponentially decayed connection times load factor of the currently running dynamic FastCGI applications. Old values are scaled by (1 - gainValue), so making it smaller weights old values more than the current value (which is scaled by gainValue). -idle-timeout n (30 seconds) The number of seconds of FastCGI application inactivity allowed before the request is aborted and the event is logged (at the 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) A name-value pair to be passed in the initial environment when instances of applications are spawned. To pass a variable from the Apache environment, don't provide the "=" (if the variable isn't actually in the environment, it will be defined without a value). To define a variable without a value, provide the "=" without any value. The option can be used repeatedly. -init-start-delay n (1 second) The minimum number of seconds between the spawning of instances of applications. This delay decreases the demand placed on the system at server initialization. -killInterval n (300 seconds) Determines how often the dynamic application instance killing policy is implemented within the process manager. Smaller numbers result in a more aggressive policy, larger numbers a less aggressive policy. -listen-queue-depth n (100) The depth of 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) The maximum number of dynamic FastCGI application instances allowed to run for any one FastCGI application. It must be <= to -maxProcesses (this is not programmatically enforced). -maxProcesses n (50) The maximum total number of dynamic FastCGI application instances allowed to run at any one time. It must be >= to -maxClassProcesses (this is not programmatically enforced). -minProcesses n (5) The minimum total number of dynamic FastCGI application instances allowed to run at any one time without being killed off by the process manager (due to lack of demand). -multiThreshold n (50) An integer between 0 and 100 used to determine whether any one instance of a FastCGI application should be terminated. If the application has more than one instance currently running, this attribute will be used to decide whether one of them should be terminated. If only one instance remains, singleThreshold is used instead. For historic reasons the mis-spelling multiThreshhold is also accepted. -pass-header header (none) The name of an HTTP Request Header to be passed in the request environment. This option makes available the contents of headers which are normally not available (e.g. Authorization) to a CGI environment. -priority n (0) The process priority to be assigned to the application instances (using setpriority()). -processSlack n (5) If the sum of the number of all currently running dynamic FastCGI applications and 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) Causes the process manager to restart dynamic applications upon failure (similar to static applications). -restart-delay n (5 seconds) The minimum number of seconds between the respawning of failed instances of applications. This delay prevents a broken application from soaking up too much of the system. -singleThreshold n (0) An integer between 0 and 100 used to determine whether the last instance of a FastCGI application can be terminated. If the process manager computed load factor for the application is lower than the specified threshold, the last instance is terminated. In order to make your executables run in the "idle" mode for the long time, you would specify a value closer to 1, however if memory or CPU time is of primary concern, a value closer to 100 would be more applicable. A value of 0 will prevent the last instance of an application from being terminated; this is the default value, changing it is not recommended (especially if -appConnTimeout is set). For historic reasons the mis-spelling singleThreshhold is also accepted. -startDelay n (3 seconds) The number of seconds the web server waits patiently while trying to connect to a dynamic FastCGI application. If the interval expires, the process manager is notified with hope it will start another instance of the application. The startDelay must be less than appConnTimeout to be effective. -updateInterval n (300 seconds) The updateInterval determines how often statistical analysis is performed to determine the fate of dynamic FastCGI applications.
FastCgiExternalServer Syntax: FastCgiExternalServer filename -host hostname:port [option ...] FastCgiExternalServer filename -socket filename [option ...] Context: server configThe 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) Unix: The number of seconds to wait for a connection to the FastCGI application to complete or 0 to indicate a blocking 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. Windows NT: TCP based applications work as above. Named pipe based applications (static applications configured without the -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). -group groupname|#gid (none) Unix (only): When FastCgiWrapper is in use, the group is used to invoke the wrapper. The -group option must be used together with -user. -idle-timeout n (30 seconds) The number of seconds of FastCGI application inactivity allowed before the request is aborted and the event is logged (at the 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) Force a write to the client as data is received from the application. By default, mod_fastcgi buffers data in order to free the application as quickly as possible. -host hostname:port (none) The hostname or IP address and TCP port number (1-65535) the application uses for communication with the web server. The -socket and -host options are mutually exclusive. -pass-header header (none) The name of an HTTP Request Header to be passed in the request environment. This option makes available the contents of headers which are normally not available (e.g. Authorization) to a CGI environment. -socket filename (none) Unix: The filename of the Unix domain socket the application uses for communication with the web server. The filename is relative to the FastCgiIpcDir. The -socket and -port options are mutually exclusive. Windows NT: The name of the named pipe the application uses for communicating with the web server. the name is relative to the FastCgiIpcDir. The -socket and -port options are mutually exclusive. -user username|#uid (none) Unix (only): When FastCgiWrapper is in use, the user is used to invoke the wrapper. The -user option must be used together with -group.
FastCgiIpcDir Syntax: Unix: FastCgiIpcDir directory Windows NT: FastCgiIpcDir name Default: Unix/Apache: FastCgiIpcDir logs/fastcgi Unix/Apache2: FastCgiIpcDir RUNTIMEDIR/fastcgi Windows NT: FastCgiIpcDir \\.\pipe\ModFastCgi\ Context: server configUnix: 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 (notice that the backslashes are escaped). The pipename 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.
FastCgiIpcDir is typically used move the directory someplace more suitable (than the default) for the platform or to prevent multiple Apache instances from sharing FastCGI application instances. FastCgiWrapper Syntax: FastCgiWrapper On | Off | filename Default: FastCgiWrapper Off Context: server configUnix (only): 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. Under Apache 1.3, they inherit their user and group from the user and group of the virtual server in which they are defined. User and Group directives must precede FastCGI application definitions. Under Apache 2.0, the -user and -group options to FastCgiServer and FastCgiExternalServer directives must be used (dynamic applications still use the virtual server's user and group). Note that access to (use of) FastCGI applications is not limited to the virtual server in which they were defined. The application is used 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 already 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).
FastCgiAuthenticator Syntax: FastCgiAuthenticator filename [-compat] Context: directoryThe 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.
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).AuthType Basic AuthName ProtectedRealm FastCgiAuthenticator fcgi-bin/authenticator require valid-user
FastCgiAuthenticatorAuthoritative Syntax: FastCgiAuthenticatorAuthoritative On | Off Default: FastCgiAuthenticatorAuthoritative On Context: directorySetting 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.
FastCgiAuthorizer Syntax: FastCgiAuthorizer filename [-compat] Context: directoryThe 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.
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).AuthType Basic AuthName ProtectedRealm AuthDBMUserFile conf/authentication-database FastCgiAuthorizer fcgi-bin/authorizer
FastCgiAuthorizerAuthoritative Syntax: FastCgiAuthorizerAuthoritative On | Off Default: FastCgiAuthorizerAuthoritative On Context: directorySetting 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.
FastCgiAccessChecker Syntax: FastCgiAccessChecker filename [-compat] Context: directoryThe 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.
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).FastCgiAccessChecker fcgi-bin/access-checker
FastCgiAccessCheckerAuthoritative Syntax: FastCgiAccessCheckerAuthoritative On | Off Default: FastCgiAccessCheckerAuthoritative On Context: directorySetting 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.
- http://wordpress.org/support/topic/105043
- http://jayallen.org/journey/2006/10/dreamhost_movable_type_and_fastcgi
- http://automatthias.wordpress.com/2006/12/01/django-on-dreamhost-incomplete-headers/
- http://forum.textdrive.com/viewtopic.php?id=1614
Handling 404 errors on Wordpress
New code from classes.php as of v. 2.1
function handle_404() { global $wp_query; // Issue a 404 if a permalink request doesn't match any posts. Don't // issue a 404 if one was already issued, if the request was a search, // or if the request was a regular query string request rather than a // permalink request. if ( (0 == count($wp_query->posts)) && !is_404() && !is_search() && ( $this->did_permalink || (!empty($_SERVER['QUERY_STRING']) && (false === strpos($_SERVER['REQUEST_URI'], '?'))) ) ) { $wp_query->set_404(); status_header( 404 ); nocache_headers(); } elseif( is_404() != true ) { status_header( 200 ); } }
Redirection on Wordpress Status problems
New code as of v. 2.1
function wp_redirect($location, $status = 302) { global $is_IIS; $location = apply_filters('wp_redirect', $location, $status); if ( !$location ) // allows the wp_redirect filter to cancel a redirect return false; $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%]|i', '', $location); $location = wp_kses_no_null($location); $strip = array('%0d', '%0a'); $location = str_replace($strip, '', $location); if ( $is_IIS ) { header("Refresh: 0;url=$location"); } else { if ( php_sapi_name() != 'cgi-fcgi' ) status_header($status); // This causes problems on IIS and some FastCGI setups header("Location: $location"); } }
HTTP 304 status not sent correctly, breaking conditional GET
http://trac.wordpress.org/ticket/3528After upgrading to WordPress 2.0.6, I noticed that my feeds were no longer working. In several browsers and readers, including Firefox, IE7, Konqueror and Akregator, only blank files were being sent. Server logs indicated a 200 response with a few hundred bytes, but browsers showed only an empty file. Oddly, Opera, Dillo, and command-line GET displayed the files fine.
Looking at the actual HTTP response headers, it turned out that on conditional GETs that were supposed to issue 304 Not Modified, the server was actually issuing the following:
HTTP/1.1 200 OK (other headers) Status: 304 Not ModifiedThis resulted in a 200 OK status and empty response body. I looked through and found that the status was being set in wp-includes/functions.php, in the status_header function. I changed the following line:
@header("Status: $header $text"); to this: @header("Status: $header $text", TRUE, $header);After making that change, status headers were sent correctly. Once I cleared the browser cache, feeds started loading again.
Going by the recommended method in the PHP manual, I also tried commenting out the if statement regarding the PHP API, so that only the following statement would run:
@header("HTTP/1.1 $header $text");This also worked correctly. This is with PHP 5.2.0 on Apache 1.3.37 (yes, I do intend to upgrade it eventually) using the mod_php interface.
FastCGI Errors with wordpress
FastCGI: comm with server "/web/user/example.com/cgi-bin/php5-wrapper.fcgi" aborted: error parsing headers: duplicate header 'Status', referer:
FIX
file: wp-includes/functions.php Change: @header("Status: $header $text");
TO: //@header("Status: $header $text");
NOTE: Since Version 2.1 you won't need to do the above. Here is the new code.
function status_header( $header ) { if ( 200 == $header ) $text = 'OK'; elseif ( 301 == $header ) $text = 'Moved Permanently'; elseif ( 302 == $header ) $text = 'Moved Temporarily'; elseif ( 304 == $header ) $text = 'Not Modified'; elseif ( 404 == $header ) $text = 'Not Found'; elseif ( 410 == $header ) $text = 'Gone'; if ( version_compare(phpversion(), '4.3.0', '>=') ) @header("HTTP/1.1 $header $text", true, $header); else @header("HTTP/1.1 $header $text"); } function nocache_headers() { @ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT'); @ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); @ header('Cache-Control: no-cache, must-revalidate, max-age=0'); @ header('Pragma: no-cache'); } function cache_javascript_headers() { $expiresOffset = 864000; // 10 days header("Content-type: text/javascript; charset=" . get_bloginfo('charset')); header("Vary: Accept-Encoding"); // Handle proxies header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT"); }
Status or HTTP 1/1?
According to fastcgi.com
How do I send an HTTP status other than 200 (the default, HTTP OK) To return an HTTP status other than 200, add a 'Status:' header from your CGI. mod_fastcgi will look for that header and set the HTTP status. The Status: header is not sent to the client, but the HTTP status (first line of the server response) is.
When php run as CGI
Place your php.ini file in the dir of your cgi'd php, in this case /cgi-bin/
htaccess might look something like this
AddHandler php-cgi .php .htm Action php-cgi /cgi-bin/php5.cgi
When cgi'd php is run with wrapper (for FastCGI)
You will have a shell wrapper script something like this:
#!/bin/sh export PHP_FCGI_CHILDREN=3 exec /user3/x.com/public_html/cgi-bin/php5.cgi
Change To
#!/bin/sh export PHP_FCGI_CHILDREN=3 exec /x.com/cgi-bin/php.cgi -c /abs/path/to/php.ini
Warning: Do not use a custom php.ini file when using fastcgi. I was contacted by DreamHost that all of my sites using this setup had been disabled until the custom php.ini was taken off.
NOTE: Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. open_basedir = ${open_basedir} ":/new/dir"
NOTE: In order for PHP to read it, config file must be named php.ini
NOTE: SetEnv PHPRC only works when using PHP as CGI, not when using php as an Apache Module
cgi.fix_pathinfo Provides real PATH_INFO/PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting this to 1 will cause PHP CGI to fix it's paths to conform to the spec. A setting of zero causes PHP to behave as before. Default is zero. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
cgi.force_redirect cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.
cgi.redirect_status_env If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.
NOTE: Setting this variable may cause security issues, know what you are doing first.
fastcgi.impersonate FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.
What's the difference between PHP-CGI and PHP as an Apache module?
The benefits of running PHP-CGI are:
- It is more secure. The PHP runs as your user rather than dhapache. That means you can put your database passwords in a file readable only by you and your php scripts can still access it!
- It is more flexible. Because of security concerns when running PHP as an Apache module, we disabled commands with the non-CGI PHP. This will cause install problems with certain popular PHP scripts if you run PHP not as a CGI!
- It's just as fast as running PHP as an Apache module, and we include more default libraries.
There are a FEW VERY MINOR drawbacks to running PHP-CGI. They are:
- Custom 404 pages won't work for .php files with PHP-CGI. Or will they?
- Variables in the URL which are not regular ?foo=bar variables won't work without using (mod_rewrite) (example.com/blah.php/username/info/variable).
- Custom php directives in .htaccess files (php_include_dir /web/user;/web/user/example_dir) won't work.
- The $_SERVER['SCRIPT_NAME'] variable will return the php.cgi binary rather than the name of your script
- Persistant database connections will not work. PHP's mysql_pconnect() function will just open a new connection because it can't find a persistant one.
If one of those is a show-stopper for you, you can easily switch to running PHP as an Apache module and not CGI, but be prepared for a bunch of potential security and ease-of-use issues! If you don't know what any of these drawbacks mean, you're fine just using the default setting of PHP-CGI and not worrying about anything!
Installed as CGI binary
One of the most common reasons why you get 'No input file specified' (AKA 'the second most useful error message in the world') is that you have set 'doc_root' (in php.ini) to a value which is to the 'DocumentRoot' defined in the apache configuration. This is the same for other webservers. For example, on lighttpd, make sure the 'server.document-root' value is the same as what is defined as 'doc_root' in php.ini.
Error Reporting
One annoying thing is that errors, even compile time ones, aren't reported until the script has had a chance to time out - 120 seconds, no less. Even then, the actual error message might not be logged, you might get only the 500 error. This means that testing under FastCGI is rather impractical. Development should be done with standard CGI, or with FastCGI disabled, or on your local computer. FastCGI should be added after the script has already been debugged.
Also, while it's tempting to develop on a live server, it's dangerous and makes you a bad neighbor for shared hosting.
To see immediately if a script will fail (won't check all cases because %ENV will be different), test it from the command line. perl ~/mydomain.com/myscript.fcgi
or for deeper checking if you can use the debugger-- perl -d ~/mydomain.com/myscript.fcgi
Restarting FastCGI processes
If you edit a script then the server will restart it from scratch the next time it's called, running the "run once" code again from the top. The server knows to do this by looking at the modification date of the script. If the process doesn't restart for some reason then you can try editing the file again so that it has a different modification date. A geeky way to accomplish the same thing is to use the Unix touch command on the file. For example: touch ~/domain/path/index.fcgi
Stopping FastCGI processes
The following command will tell the FastCGI process to end after it has finished any requests it is handling. killall -USR1 dispatch.fcgi
(replace dispatch.fcgi with the name of the process) The above command may not always convince all the proccesses to stop. To force them to stop use: killall -9 dispatch.fcgi
(replace dispatch.fcgi with the name of the process) Occasionally you may have to use ruby1.8 as a task ID: killall -9 ruby1.8
My FastCGI Isn't working
Check your .htaccess file for
AddHandler fastcgi-script .fcgi Options +FollowSymLinks +ExecCGI
Also, I found that I had the following directive: RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
That needed to be changed to: RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
In response to grange at club-internet dot fr: There are a couple of errors in the mod_rewrite directives given. I found that the following works: RewriteEngine on RewriteCond %{ENV:REDIRECT_STATUS} !200 RewriteRule ^cgi-bin/php.cgi - [F] I removed the = from the RewriteCond and took out the leading / from the RewriteRule.
I have noticed that some people have noted that running PHP as a CGI program can run slowly compared with a compiled in module. Some have noted that they want to use FastCGI but are hesitant. I found that using the Apache 2's CGID module was a great way to speed up performance almost to the same level as an "so"-installed PHP module but you get the added benefit of running each virtual host under it's own user and group. In my testing I got 44 pages per second using PHP as a module and I got roughly the same performance (within 5%) running PHP as a CGI program through CGID. CGID is also really easy to set up. Just add --enable-cgid to your Apache configure command and you're good to go. Just set up PHP as a CGI normally. I'm sure that there's extra RAM used for this method but RAM is as cheap as borscht anyways so it shouldn't be a major factor when trying to speed up PHP CGI.
Here are my two cents of knowledge about php-cgi when running CGI script from prompt: If you get the "No input file specified." error, create the environment variable "SCRIPT_FILENAME=C:filestest.php". If you get "Security Alert!" error and it tells you to create the REDIRECT_STATUS environment variable, it is because you have the SERVER_NAME variable set but not the REDIRECT_STATUS variable. Hence, if you have SERVER_NAME, you also need REDIRECT_STATUS, but not otherwise. And you pretty much should have SCRIPT_FILENAME at all time.
--enable-force-cgi-redirect won't work in FastCGI mode : as of 4.3.10, it is only supported in CGI mode. However, you can achieve the same result with mod_rewrite under Apache : RewriteEngine on RewriteCond %{ENV:REDIRECT_STATUS} !=200 RewriteRule /cgi-bin/path/to/php - [F] This will only allow internal redirection, thus forbidding direct HTTP access to php interpreter (http://www.exemple.com/cgi-bin/path/to/php).
PHP CGI with VirtualHosts. This is what I found out while trying to get php to work as CGI with Apache VirtualHosts. By enabling 'force-cgiredirects', you *must*: 1) set 'cgi.fix_pathinfo=1' in php.ini 2) leave doc_root commented out (php.ini also) If you miss item 1, the apache logs will show 'unexpected T_STRING' in the php binary. If you miss item 2, you'll only see 'No input file specified.', instead of the expected output. You can then turn on the php support for a particular vhost by defining: Action php-script /cgi-bin/php inside the correspondingdirective.
PHP works with Apache and suEXEC like this: (Assuming that suEXEC ist allready installed and working) Install PHP as CGI binary (e.g. in /usr/local/bin/php) (compile with --enable-force-cgi-redirect) Create a Link inside cgi-bin directory to make php-cgi accessable: cd /usr/local/apache/cgi-bin ln /usr/local/bin/php php Edit your httpd.conf file: AddHandler php4-script .php Action php4-script /cgi-bin/phpUser exampleuser Group examplegroup ... Restart Apache PHP-scripts are now called under the user-id of exampleuser and group-id of examplegroup.
a replacement for suexec is suphp (http://www.suphp.org). "suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter." (from the website)
I have setup a guide to installing PHP with SuEXEC in such a way that shebangs (!#/usr/bin/php4) are not needed. Hope this is of some help to you.
A tip for Windows-users Just a tip for you so do not do the same mistake as I did: I just found out that PHP first seem to look in the php-directory for php.ini, and if that file does not exist, it looks in the Windows directory. I renamed the file php.ini-dist to php.ini and copied it to my Windows directory, and then I modified the infamous "cgi.force_redirect = 0" in the php.ini file located in the Windows directory, to make it work. But it did not because it reads from the "original" php.ini - So when I deleted this php.ini things started working again
If you are using php per cgi and have additionally mod_gzip enabled you have to disable mod_gzip for the php cgi binary to use --enable-cgi-redirect. mod_gzip sets the REDIRECT_STATUS always to 200 which makes it impossible for the php binary to know when it was called directly or when it was called by a redirect.
To use php-cgi with suexec it will be nice that each virtual host has ist's own php.ini. This goes with : SetEnv PHPRC /var/www/server/www.test.com/conf But suexec will kill this enviromet cause It don't know that it is "save" so you must edit the suexec.c for compiling ....
When using php in cgi mode, it's often a good idea to take a look at the apache suexec feature in addition to the --force-cgi-redirect option. /aa/docs/suexec.html
If you do virutal hosting, you can turn safe mode on and off for different Apache Virutal Hosts using the php_admin_value directive. This also allows you to have customised maximum execution times, disabled functions, etc; anything which is set in php.ini. Note that by placing a base_dir for each virutal host, this means PHP CANNOT access files below this heirachy; strongly recomended for customer hosting. Example (httpd.conf): [VirtualHost 127.0.0.1:80] DocumentRoot /var/www/html/safephphost/ ServerName safephp php_admin_value safe_mode 1 php_admin_value open_base_dir /var/www/html/safephphost/ php_admin_value sendmail_from phobo#paradise.net.nz [/VirtualHost] Am not sure which versions this started working with but does with Apache 1.3.19/PHP4.04pl1.
If you care about security, you are better of setting register_globals = off enable_track_vars = on (Always on from PHP4.0.3) Default setting for variable order is EGPCS (ENV VARS/GET VARS/POST VARS/COOKIE VARS/SESSION VARS) Imagine if you are rely on ENV VAR but it was orver written with GET/POST/COOKIE vars?
If you want to use suexec and reference your php interpreter via #!/usr/local/bin/php, be shure to compile php WITHOUT --enable-force-cgi-redirect. This might seems obvious, but I spent 2 days on this :-(
The configuration option '--enable-force-cgi-redirect' is supported by Zeus Web Server 3.3.8.2 (at least, that's what I've tried it on - it make work on previous versions).
suEXEC require CGI mode, and slow down the scripts. I did them like this: 1. Install php as DSO mode. (for max speed and low secure) 2. Make a seperate CGI install with --enable-force-cgi-redirect, place php to cgi-bin 3 For more secure with suEXEC, choose one of the following method: 3-1: Place a .htaccess file containing this to override main config: AddType application/x-httpd-wphp php Action application/x-httpd-wphp /cgi-bin/php All php files in subdirectory will be protected. 3-2: add following in httpd.conf: AddType application/x-httpd-wphp sphp Action application/x-httpd-wphp /cgi-bin/php then each sensitive php file should be renamed to .sphp Add "php_value doc_root /web/user/html_docs" to each virtual host directive in httpd.conf
another clean solution is to hack suexec.c of apache and force all .php scripts to be executed with php compiled in cgi mode. suexec.c in place if (!(prg_info.st_mode & S_IXUSR)) { just if (!(prg_info.st_mode & S_IXUSR) & (strstr(cmd, ".php") == NULL)) { in place execv(cmd, &argv[3]); just if (strstr(cmd, ".php")) { execl("/usr/local/bin/php", "php", cmd, NULL); } else { execv(cmd, &argv[3]); }
Better yet, use binfmt_misc: (linux only) echo :php3:E::php3::/usr/bin/php: > /proc/sys/fs/binfmt_misc/register Eliminates the need for the #! at the top of the file.
Comments