wiki'd

by JoKeru

Serve PHP via FastCGI in Apache on Ubuntu

The default Apache/PHP setup uses mpm_prefork which starts an Apache process for each HTTP request. Every process has an embedded mod_php interpreter to deliver fast a php page. But not all requests are php pages, there are also a lot of static requests like js, css, images, html and on. This embedded module makes each process very RAM intensive. If you have tons of RAM or if you have a low traffic site, this is no problem.

But if you run a high traffic site or if your resources are limited, you need to change this behavior. You'll need to install Apache (version 2.4+) Worker MPM (Multi-Procesing Modules, replaces the prefork), PHP and PHP FastCGI Process Manager. The mod_proxy_fcgi module is a new one and it allows Apache to connect to/forward requests to an external FastCGI process manager like php-fpm, allowing a complete separation between the running of PHP scripts and Apache. Earlier we had to use modules like mod_fcgid and mod_fastcgi which all had some limitations.

[cc lang='bash']
# Ubuntu 14.04 LTS
\$ apt-get install apache2-mpm-worker
\$ a2enmod proxy_fcgi
\$ apt-get install php5-fpm php5

# php-fpm listens by default on a unix socket - /var/run/php5-fpm.sock
# but mod_proxy_fcgi from apache 2.4.7 does not work with unix sockets (from 2.4.9 it supports unix sockets)
# so we'll need to use tcp sockets for the communication between apache and php-fpm
\$ echo 'listen = 127.0.0.1:9000' >> /etc/php5/fpm/pool.d/www.conf
\$ service php5-fpm restart

# add the following line to your Apache Virtual Host configuration
ProxyPassMatch \^/(.*\.php(/.*)?)\$ fcgi://127.0.0.1:9000/var/www/html/\$1

\$ service apache2 restart
[/cc]

UPDATE - having some problems with phpMyAdmin, so here is mod_fastcgi implementation:
[cc lang='bash']
# Ubuntu 14.04 LTS
\$ apt-get install apache2-mpm-worker
\$ apt-get install php5-fpm php5

\$ cat \<\<'EOF' >> /etc/apt/sources.list
deb http://archive.ubuntu.com/ubuntu trusty multiverse
deb http://archive.ubuntu.com/ubuntu trusty-updates multiverse
deb http://security.ubuntu.com/ubuntu trusty-security multiverse
EOF
\$ apt-get update
\$ apt-get install libapache2-mod-fastcgi
\$ a2enmod actions alias fastcgi
\$ cat \<\<'EOF' > /etc/apache2/conf-available/php5-fpm.conf

AddHandler php5-fcgi .php
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization

EOF
\$ a2enconf php5-fpm
\$ cat \<\<'EOF' >> /etc/apache2/sites-enabled/000-default.conf

Require all granted

EOF
\$ service apache2 restart
[/cc]

more details: http://wiki.apache.org/httpd/PHP-FPM

Comments