Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 30 ยท Serving Content

PHP, FastCGI and Application Servers

Connect nginx and Apache to PHP-FPM with FastCGI, set up a front controller with try_files or mod_rewrite, compare mod_php and proxy_fcgi, and reach uwsgi and Node.

A web server is excellent at files and terrible at running your code. Nginx cannot execute PHP, Python or Ruby by itself, and you would not want it to: an application crash should not take the web server down with it. The standard design is to keep them separate. The web server owns the sockets, TLS and static files, and forwards the requests that need code to an application server over a small protocol.

For PHP, that protocol is FastCGI and the application server is PHP-FPM (FastCGI Process Manager). In this lesson you will see what a FastCGI request looks like, configure nginx and Apache for PHP-FPM, build the front controller that Laravel-style applications need for clean URLs, compare Unix sockets with TCP, understand why mod_php is fading, and meet the similar setups for uWSGI and Node.js.

The real configuration in this lesson is read-only, because the site cannot run a web server or PHP-FPM. The interactive examples are JavaScript stand-ins that model the routing decisions and the data a web server hands to FastCGI. They are not nginx, Apache or PHP-FPM.

How FastCGI works

Plain CGI starts a new program for every request, which is slow. FastCGI keeps worker processes alive and talks to them over a connection. The web server turns each HTTP request into a set of name/value parameters plus the request body, sends them to a worker, and streams the worker's response back to the client.

Who does what

Web server Sockets, TLS, static files, routing.
FastCGI A compact protocol between the two.
PHP-FPM A pool of long-lived PHP workers.

One request, three players, each with one job.

1 / 2

PHP-FPM runs as its own service with one or more pools, configured in files such as /etc/php/8.4/fpm/pool.d/www.conf on Debian. Two settings matter first:

INI
; where to listen
listen = /run/php/php8.4-fpm.sock
; or: listen = 127.0.0.1:9000

; how many PHP workers
pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6

pm.max_children is the hard ceiling of simultaneous PHP requests. Set it from memory: if one PHP worker uses about 60 MB and you can spare 1.5 GB, that is roughly 25 workers. Too high and the machine swaps; too low and requests wait in a queue.

Nginx with PHP-FPM

A complete nginx setup for a typical framework application (Laravel, Symfony, WordPress with pretty permalinks) has two location blocks:

NGINX
server {
    listen 80;
    server_name app.example.com;
    root /var/www/app/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    }

    location ~ /\.(?!well-known) {
        deny all;
    }
}

Read it from the top. try_files $uri $uri/ /index.php?$query_string; says: if the URL is a real file, serve it; if it is a directory, use that; otherwise hand the request to index.php, keeping the query string. That last fallback is the front controller pattern: one PHP file receives every URL that is not a file, and the framework's router decides what to do with it. The location ~ \.php$ block sends PHP files to PHP-FPM; fastcgi_params is a file of standard parameter lines shipped with nginx, and SCRIPT_FILENAME tells PHP-FPM which file to run. $realpath_root resolves symlinks, which keeps opcache working correctly after symlink-based deploys. The last block blocks hidden files such as .env and .git while allowing /.well-known/ for certificate validation.

The classic mistake is a location ~ \.php$ that runs any .php file under the root. If your app accepts uploads, an attacker who gets a shell.php into an upload folder can execute it. For a front-controller app, let only index.php run: use location = /index.php { ... } for the FastCGI block and location ~ \.php$ { return 404; } for every other .php URL. Keep PHP-FPM's security.limit_extensions at its default of .php, and set cgi.fix_pathinfo=0 in php.ini so a request like /uploads/pic.jpg/x.php can never run pic.jpg as PHP.

The stand-in below mimics try_files, the front controller, and the two safety rules. Change the file sets and the requests and watch which component answers.

JS Stand-in: a front-controller router

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The important rows: /blog/42 is not a file, so the front controller runs and the application decides what /blog/42 means. /.env is stopped by the web server before PHP is involved. /uploads/shell.php exists on disk but never runs. Static assets never touch PHP at all, which is why they stay fast no matter how heavy the application is.

What the web server sends to PHP-FPM

PHP's superglobals ($_SERVER, $_GET) are filled from the FastCGI parameters. Seeing them once makes many mysteries disappear: if SCRIPT_FILENAME points at the wrong place, PHP-FPM answers "File not found."; if QUERY_STRING is missing, $_GET is empty. The next stand-in builds the parameter set the way the config above does, including the splitting of a trailing path (fastcgi_split_path_info).

JS Stand-in: building FastCGI parameters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last lines of output are a warning, not a bug: a classic PHP deployment weakness happened when the web server forwarded such a URL and PHP guessed the "real" script by trimming path segments. Modern defaults close this hole, but only if you keep cgi.fix_pathinfo=0 and do not run arbitrary .php files.

Sockets or TCP?

PHP-FPM can listen on a Unix domain socket (/run/php/php8.4-fpm.sock) or a TCP port (127.0.0.1:9000).

  • A Unix socket is a file. It skips the TCP stack, so it is a little faster, and access is controlled with file permissions: set listen.owner, listen.group and listen.mode in the pool so the web server's user may connect. The usual error when this is wrong is connect() to unix:/run/php/php8.4-fpm.sock failed (13: Permission denied) in the nginx error log.
  • TCP is required when PHP-FPM runs on another machine or in another container (fastcgi_pass php:9000; in Docker Compose). It is also easy to debug with tools. Never bind it to a public address: FastCGI has no authentication, and anyone who can reach it can run code.

For very busy servers also raise listen.backlog and the kernel's somaxconn so that bursts queue instead of failing. Tuning is covered in Performance Tuning.

Apache: mod_php versus proxy_fcgi

Apache has two ways to run PHP. The old way is mod_php, which embeds the PHP interpreter in every Apache process. It is simple, but it forces the prefork MPM (the non-threaded one), every worker carries PHP's memory even when serving images, and PHP runs with Apache's privileges. The modern way is mod_proxy_fcgi with PHP-FPM, exactly like nginx: it works with the event MPM (see Apache httpd Configuration) and lets static files bypass PHP entirely.

Terminal
sudo a2enmod proxy_fcgi setenvif rewrite
sudo a2enconf php8.4-fpm    # Debian ships a ready-made snippet; or add the block below
sudo systemctl reload apache2
APACHE
<VirtualHost *:80>
    ServerName app.example.com
    DocumentRoot /var/www/app/public

    <Directory "/var/www/app/public">
        AllowOverride None
        Require all granted

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ index.php [L]
    </Directory>

    <FilesMatch "\.php$">
        SetHandler "proxy:unix:/run/php/php8.4-fpm.sock|fcgi://localhost"
    </FilesMatch>
</VirtualHost>

The RewriteCond pair plays the role of try_files: if the request is neither a file nor a directory, serve index.php. On Apache 2.4 there is an even shorter way for the front controller, FallbackResource /index.php, which sends everything that does not exist to that URL without needing mod_rewrite. The unix: form in SetHandler needs Apache 2.4.10 or newer. Compare the rewrite syntax with Redirects and Rewrites.

Other application servers

The same pattern holds for other languages; only the protocol and the directive change.

  • Python: WSGI applications run under uWSGI or Gunicorn. Nginx has native uwsgi_pass unix:/run/uwsgi/app.sock; with include uwsgi_params;, while Gunicorn is usually reached with proxy_pass over HTTP. Apache can embed Python with mod_wsgi or proxy to the app server.
  • Node.js, Go, Java and others speak HTTP themselves, so the web server simply proxies to them (proxy_pass http://127.0.0.1:3000;, ProxyPass in Apache). That is the subject of Reverse Proxy Basics.

In every case the web server stays in front, serving static files itself and forwarding only what needs code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does try_files $uri $uri/ /index.php?$query_string; implement?

    The directive tries the file, then the directory, then falls back to index.php with the original query string, so one script can route every pretty URL.
  2. 2. Why is location ~ \.php$ with fastcgi_pass dangerous for an application that accepts uploads?

    Any file ending in .php under the root is handed to PHP. Let only the front controller run, and answer 404 for every other .php URL.
  3. 3. What is the main advantage of mod_proxy_fcgi with PHP-FPM over mod_php?

    mod_php embeds PHP in every Apache process and requires prefork. With FastCGI, Apache workers stay small and PHP is sized separately.
  4. 4. PHP-FPM listens on 127.0.0.1:9000 and the nginx error log shows 'connect() failed (111: Connection refused)'. What is a likely cause?

    Connection refused means nothing is accepting connections at that address. Check the PHP-FPM service and its listen setting.

Summary

  • Web servers forward dynamic requests to an application server; for PHP the protocol is FastCGI and the server is PHP-FPM.
  • Nginx uses fastcgi_pass plus try_files for the front controller; Apache uses proxy_fcgi with SetHandler and either FallbackResource or the RewriteCond pair.
  • Run only index.php for framework apps, block hidden files, and keep cgi.fix_pathinfo=0.
  • Unix sockets are faster and permission-controlled; TCP is for other hosts and containers and must never be public.
  • mod_php needs the prefork MPM and is largely replaced by PHP-FPM.
  • Python and other apps use uwsgi or plain HTTP proxying, covered next.

Next: Reverse Proxy Basics.