How to Set Up Nginx FastCGI Caching with PHP-FPM on Ubuntu 24.04
Cache PHP pages in Nginx on Ubuntu 24.04 so repeat requests skip PHP-FPM and the database, with safe bypass rules, a test procedure and cache clearing.
Nginx can store the pages that PHP-FPM generates and serve them again without running PHP or touching the database. For pages that look the same to every visitor, this FastCGI cache is the cheapest performance gain available on a small server. This guide sets it up on Ubuntu 24.04 with the distribution's Nginx 1.24 and PHP 8.3; on Ubuntu 22.04 the steps are identical apart from the PHP version in the socket path.
Ubuntu 12.04 and PHP 5, which older versions of this guide used, are end-of-life. The MySQL or MariaDB side of the stack is not affected by page caching and is installed the usual way as part of a LEMP setup, so it is not repeated here.
Requirements
- A server running Ubuntu 24.04 and a user that can run
sudo. - A domain pointing at the server. The examples use
example.comwith the site in/var/www/example.com/public. - A PHP site or application. A test script is included below.
Install Nginx and PHP-FPM
Skip this step if both are already installed.
sudo apt update
sudo apt install nginx php-fpmOn Ubuntu 24.04 the php-fpm package installs PHP 8.3, and PHP-FPM listens on the socket /run/php/php8.3-fpm.sock. Confirm the exact name on your system:
ls /run/php/Define the cache
Create a directory for the cached files, owned by the user Nginx runs as:
sudo mkdir -p /var/cache/nginx/fastcgi
sudo chown www-data:www-data /var/cache/nginx/fastcgiThe cache itself is declared once in the http context. Files in /etc/nginx/conf.d/ are included there, so create one:
sudo nano /etc/nginx/conf.d/fastcgi-cache.conffastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=PHPCACHE:100m max_size=1g inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";levels=1:2spreads the files over two levels of subdirectories.keys_zone=PHPCACHE:100mnames the cache and reserves 100 MB of shared memory for its index. One megabyte holds about 8,000 keys, so a smaller zone is fine on a low-memory server.max_size=1gcaps the disk space; when it is reached Nginx removes the least recently used entries.inactive=60mremoves entries nobody has requested for an hour, whether or not they are still fresh.use_temp_path=offwrites files directly into the cache directory instead of copying them from a temporary location.fastcgi_cache_keydecides what counts as the same page. Including the scheme, method, host and full URI keeps different sites and query strings apart.
Enable caching in the server block
Create or edit the site's configuration:
sudo nano /etc/nginx/sites-available/example.comserver {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/public;
index index.php index.html;
# Decide which requests must never be cached
set $skip_cache 0;
if ($request_method = POST) {
set $skip_cache 1;
}
if ($request_uri ~* "^/(admin|login|cart|checkout|wp-admin|wp-login\.php)") {
set $skip_cache 1;
}
if ($http_cookie ~* "PHPSESSID|wordpress_logged_in|comment_author") {
set $skip_cache 1;
}
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;
fastcgi_cache PHPCACHE;
fastcgi_cache_valid 200 301 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache_use_stale error timeout updating http_500 http_503;
fastcgi_cache_lock on;
add_header X-Cache-Status $upstream_cache_status always;
}
}The important parts:
fastcgi_cache_validsets how long a response with a given status code stays fresh. Ten minutes is a reasonable start for a blog or brochure site; raise it when content changes rarely.fastcgi_cache_bypassstops Nginx from answering out of the cache, andfastcgi_no_cachestops it from saving the response, whenever$skip_cacheis 1. Use both together, and adjust the URL and cookie patterns to the paths and session cookie names of your own application.fastcgi_cache_use_stalelets Nginx serve an expired copy when PHP-FPM returns an error or times out, and while a fresh copy is being generated.fastcgi_cache_lock onsends only one request to PHP when many visitors ask for the same uncached page at once.- The
X-Cache-Statusheader exposes what happened to each request, which makes testing easy. Remove it later if you do not want it public.
Enable the site, remove the default one if it is still active, then test and reload:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl reload nginxVerify that pages are cached
Create a script whose output changes every second:
sudo mkdir -p /var/www/example.com/public
echo '<?php echo date("H:i:s");' | sudo tee /var/www/example.com/public/time.phpRequest it twice and look at the status header:
curl -s -D - http://example.com/time.php
curl -s -D - http://example.com/time.phpThe first response shows X-Cache-Status: MISS. The second shows HIT and the same time as the first, because PHP did not run again. Other values you will meet are BYPASS (a skip rule matched), EXPIRED (the entry was too old and has been refreshed) and STALE or UPDATING (an old copy was served on purpose). Delete the test script afterwards:
sudo rm /var/www/example.com/public/time.phpTroubleshooting: every request is a MISS
Nginx respects what the application says about caching. A response is not stored when it carries a Set-Cookie header, or when Cache-Control or Expires forbid caching. PHP sends exactly such headers as soon as a script calls session_start(), and many applications start a session on every page.
Check the headers PHP returns:
curl -s -o /dev/null -D - http://example.com/The clean fix is in the application: do not start sessions or set cookies for anonymous visitors. If that is not possible, you can tell Nginx to ignore the caching headers in the PHP location:
fastcgi_ignore_headers Cache-Control Expires;Do not add Set-Cookie to that list unless you fully understand the consequences: a cached response would then include one visitor's cookie and hand it to everybody else.
Clear the cache
Open-source Nginx has no purge command; the fastcgi_cache_purge directive belongs to the commercial version. To empty the whole cache after a deployment or content change, delete the files:
sudo find /var/cache/nginx/fastcgi -type f -deleteNginx notices the missing files and regenerates pages on the next request. No reload is needed.
Frequently asked questions
How is this different from OPcache?
OPcache stores compiled PHP code, so scripts start faster but still run and still query the database on every request. The FastCGI cache stores the finished HTML, so PHP does not run at all on a hit. They complement each other; keep OPcache enabled.
Can I cache pages for logged-in users?
Not safely with a shared cache like this one, because the page content depends on who is asking. Keep the cookie rule that bypasses the cache for sessions, and cache only what anonymous visitors see.
Can I keep the cache in memory instead of on disk?
You can point fastcgi_cache_path at a tmpfs mount, but the Linux page cache already keeps frequently read cache files in RAM, so the gain is usually small and the memory is lost to everything else on a small server.
How long should pages stay cached?
As long as you can tolerate visitors seeing an old version. Even one minute removes almost all PHP load during a traffic spike, because thousands of requests collapse into one per page per minute.