Sub topic 7
Connecting Nginx to PHP-FPM with FastCGI
This chapter assumes you can edit files and install packages on a Debian or Ubuntu server, and that you know HTTP status codes and headers. It also assumes you have a small PHP application and Nginx installed. You should know what a server block and a location are. Earlier chapters covered both, along with PHP-FPM pools and Unix sockets.
What Nginx does not do
Nginx has no PHP interpreter. It cannot run .php files. When a request needs PHP, Nginx hands it to a separate process, PHP-FPM, and relays the answer to the client. The protocol they speak is FastCGI. It is a binary protocol that carries the request metadata (method, path, query string, headers) and the request body from Nginx to PHP-FPM. It carries the response back.
Nginx does not send the HTTP request as it arrived. It builds a set of named parameters, such as SCRIPT_FILENAME, QUERY_STRING and REQUEST_METHOD. PHP-FPM turns these parameters into the $_SERVER array and the environment of your script. Most FastCGI problems come from one of these parameters being wrong or missing, so the configuration below is mostly about setting them correctly.
Installing the pieces
On Ubuntu or Debian, install Nginx and the FPM package for your PHP version. The package name includes the version number.
sudo apt update
sudo apt install nginx php8.3-fpm
sudo systemctl enable --now php8.3-fpm
ls -l /run/php/The ls shows the socket that PHP-FPM listens on, normally /run/php/php8.3-fpm.sock. The socket path and the version number depend on your distribution and the PHP version you installed. Check them before you copy a configuration.
The server block
This block serves files from the public directory, routes unknown paths to index.php, passes .php requests to PHP-FPM, and denies hidden files.
server {
listen 80;
server_name example.com;
root /var/www/example/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
location ~ /\.(?!well-known) {
deny all;
}
}Save it as /etc/nginx/sites-available/example, link it into sites-enabled, and test it before you reload. The snippet path and the sites-available layout are Debian and Ubuntu conventions. Other distributions put configuration under /etc/nginx/conf.d/ and may not ship the snippet.
Each part in turn
root /var/www/example/public;sets the base directory. Point it at the public directory of your application, not the project root. Source code,.envfiles andvendor/then stay outside the document root and cannot be requested.index index.php;makes a request for/tryindex.phpin the directory.location /withtry_fileschecks whether the URI is a file, then a directory, and otherwise rewrites internally to/index.phpwith the original query string. Frameworks such as Laravel and Symfony rely on this front-controller pattern. Static files are served by Nginx without involving PHP.location ~ \.php$is a regular expression location. It catches any URI that ends in.php, and its job is to hand the request to FPM.fastcgi_passnames where PHP-FPM listens. Theunix:prefix means a Unix socket path. For TCP you would writefastcgi_pass 127.0.0.1:9000;.location ~ /\.(?!well-known)matches any path segment that begins with a dot, such as.gitor.env, except.well-known. That directory must stay reachable for certificate validation, which a later chapter covers.
What the snippet contains
The line include snippets/fastcgi-php.conf; hides the important details. On Debian and Ubuntu, the file looks roughly like this:
# regex to split $uri to $fastcgi_script_name and $fastcgi_path_info
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;
# Bypass the fact that try_files resets $fastcgi_path_info
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;
fastcgi_index index.php;
include fastcgi.conf;Read your own copy, since it can differ between versions. Three points matter.
try_files $fastcgi_script_name =404;returns a 404 if the script does not exist. Without it, a request such as/uploads/photo.jpg/x.phpcould be passed to PHP-FPM, which might run an uploaded file. This is the classic path-info vulnerability. The check, together withcgi.fix_pathinfo=0inphp.ini, closes it.fastcgi_split_path_infoseparates/index.php/users/5into the script (/index.php) and the extra path (/users/5), which PHP receives asPATH_INFO.include fastcgi.conf;loads the standard list offastcgi_paramlines. The most important one is:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;PHP-FPM uses SCRIPT_FILENAME to decide which file to run. If it is missing or wrong, FPM answers "File not found." or "Primary script unknown", and the browser shows a blank page or a 404.
If you write the location by hand instead of using the snippet, you need at least include fastcgi_params; and your own SCRIPT_FILENAME line. The older fastcgi_params file does not set SCRIPT_FILENAME. The newer fastcgi.conf does.
Socket or TCP
A Unix socket is a file. It avoids the network stack, and file permissions control who can connect. A TCP port is needed only if PHP-FPM runs in another container or on another host. If you use a socket, the Nginx worker user (usually www-data) must be able to open it. That is set in the FPM pool file, for example /etc/php/8.3/fpm/pool.d/www.conf:
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660If these values do not match the user Nginx runs as, every PHP request fails with a 502.
Timeouts and buffers
Defaults suit most pages. Change them only for a reason you can name.
| Directive | Default | Effect |
|---|---|---|
| `fastcgi_connect_timeout` | 60s | How long Nginx waits to connect to FPM |
| `fastcgi_read_timeout` | 60s | How long Nginx waits between reads of the response |
| `fastcgi_send_timeout` | 60s | How long Nginx waits between writes of the request |
| `fastcgi_buffers` | 8 buffers of one page | Memory for the response from FPM |
A 504 Gateway Timeout means FPM did not answer within fastcgi_read_timeout. Raising the timeout hides a slow script. For a legitimately long job, such as an export, raise it only on that one location. Keep PHP's own max_execution_time in line with it.
Applying and checking the change
Always test the configuration before you reload. A reload with a syntax error is refused and the old configuration keeps running, but testing first shows you the exact line.
sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/example
sudo nginx -t
sudo systemctl reload nginx
echo '<?php phpinfo();' | sudo tee /var/www/example/public/info.php
curl -I http://example.com/info.php
sudo rm /var/www/example/public/info.phpThe last command removes the test file. A phpinfo() page exposes configuration details, so it must not stay on a live server. A 200 OK response with Content-Type: text/html shows that the whole chain works.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| 502, log says `connect() to unix:... failed (2: No such file or directory)` | Wrong socket path or PHP version, or FPM not running | Compare `fastcgi_pass` with `ls /run/php/`; run `systemctl status php8.3-fpm` |
| 502, log says `(13: Permission denied)` | Nginx user cannot open the socket | Fix `listen.owner`, `listen.group`, `listen.mode` in the pool file and restart FPM |
| 404 with a blank body on `.php` URLs, log says `FastCGI sent in stderr: "Primary script unknown"` | `root` or `SCRIPT_FILENAME` points to a file that does not exist | Check `root` and that `fastcgi.conf` is included |
| 403 Forbidden | No `index` file in a directory, or Nginx cannot read the directory | Check `index` and the permissions on every parent directory |
| Browser downloads the PHP source | The `.php` location did not match, so Nginx served the file as plain content | Check the regex location and reload Nginx |
| 504 Gateway Timeout | A script ran longer than `fastcgi_read_timeout` | Find the slow query or raise the timeout for that location only |
A downloaded PHP source file is a security incident, not a cosmetic bug, because it can expose database passwords. Fix it before anything else.
For errors that Nginx does not explain, look at the PHP-FPM log, for example /var/log/php8.3-fpm.log, and at the pool's slow log if you enabled it. Fatal PHP errors appear in whichever log error_log in php.ini or the pool configuration names.
Review
The chain has four links. Nginx matches a location. It builds FastCGI parameters, above all SCRIPT_FILENAME. It connects to the FPM socket, and the pool's worker runs the script. Each failure in the table above maps to one link, so you can find a fault by asking which link broke.
Exercise
Requests to /index.php return 502. The Nginx error log shows "connect() to unix:/run/php/php8.2-fpm.sock failed (2: No such file or directory)", and you installed php8.3-fpm. What is wrong, and how do you fix it?
Show answer
The fastcgipass directive names a socket for PHP 8.2, but the installed FPM service listens on /run/php/php8.3-fpm.sock. Run ls /run/php/ to confirm the real socket name, change fastcgipass to unix:/run/php/php8.3-fpm.sock, run sudo nginx -t, and then sudo systemctl reload nginx.
Exercise
Why does the snippet contain tryfiles $fastcgiscript_name =404, and what could happen without it?
Show answer
It makes Nginx return 404 when the script named in the URL does not exist on disk. Without it, a URL such as /uploads/image.jpg/x.php could be passed to PHP-FPM. If PHP resolved the path to the uploaded image and executed it, an attacker could run code hidden in an upload. Setting cgi.fix_pathinfo=0 in php.ini gives a second layer of protection.