Mikey Boldt About Contact

Configure <code>.htaccess.</code> to use FastCGI for PHP

· Tech

Introduction

I had a request to use FastCGI for PHP handling on a wordpress site, to fix permissions issues. That is, FastCGI runs the PHP scripts as the owner instead of the apache user. This plays more nicely with e.g. file uploads and script-generated files. Here’s a link for More info on PHP handlers.

The configuration was a little tricky, and I didn’t find a single site that laid it all out easily. Here are the steps:

Ensure mod_fcgid is loaded

Check that this line appears in httpd.conf:

LoadModule fcgid_module /usr/lib/httpd/modules/mod_fcgid.so

Create a wrapper script

I don’t fully grok it, but mod_fcgid must run the CGI scripts using suexec. suexec expects everything it runs to be inside the its document root. This document root can be found by running the command (as root):

/usr/sbin/suexec -V

and looking for the value of AP_DOC_ROOT. Mine is /var/www.

So, we make a wrapper script for the PHP CGI handler underneath the document root. We can set other relevant variables in there. Here’s an example, which I put in /var/www/cgi-bin/php-fastcgi:

#!/bin/sh
PHPRC=/etc/
export PHPRC # php.ini directory.
export PHP_FCGI_MAX_REQUESTS=5000 # Num requests before restarting process.
export PHP_FCGI_CHILDREN=8
exec /usr/bin/php-cgi # Call the regular PHP handler.

Update .htaccess settings

Now, we tell the web server ot run PHP scripts using fcgid:

AddHandler fcgid-script .php
Options +ExecCGI
FcgidWrapper /var/www/cgi-bin/php-fcgi .php

I believe this can also be done in httpd.conf, but this was my solution.

Done

We can see that it worked by looking at the “Server API” line in phpinfo(); it should have changed from e.g. “Apache 2.0 Handler” to “CGI/FastCGI”.

Tags: Apache, Fastcgi, Htaccess, Mod_fcgid, Php