Mastering Zero-Build Cache Busting on Nginx + PHP: From ?v= to immutable
- Introduction & The History of Cache Busting
- The Quick & Clean Fix: Dynamic ?v={TIMESTAMP}
- Understanding Cache-Control: public, max-age=31536000, immutable
- Going One Step Further: Filename Versioning (styles.1795591200.css)
- Under the Hood: Resource Costs & Apache vs. Nginx Reality
- Production Tuning: nginx.conf, php.ini, & PHP-FPM (8GB RAM VPS Blueprint)
- Summary Decision Matrix
Introduction & The History of Cache Busting
- The Problem: In the early 2000s (the Internet Explorer 6 and Web 2.0 era), web developers faced a dilemma: aggressive browser caching made sites fast, but deploying CSS or JavaScript updates meant users saw broken layouts until they cleared their cache (Ctrl + F5).
- The Pioneers: While no single person invented cache busting, the practice was formalized between 2006 and 2008 by web performance pioneers—most notably Steve Souders (author of High Performance Web Sites and creator of YSlow at Yahoo!/Google) and Paul Irish (creator of HTML5 Boilerplate in 2010).
- The Core Rule: Souders popularized the “Far Future Expires” rule: tell browsers to cache static assets forever, and change the URL whenever the file changes.
- Why This Matters Today: Modern frontend stacks use Webpack, Vite, or Rollup to generate content hashes (app.8f92c1.js). However, if you manage dozens of lightweight PHP sites on a single VPS without a Node.js build pipeline, server-side filemtime() cache busting gives you the exact same performance with zero build overhead.
The Quick & Clean Fix: Dynamic ?v={TIMESTAMP}
For 90% of single-server setups, appending the file’s last-modified Unix timestamp as a query string is the fastest, cleanest solution.
Step 1: The PHP Helper Function
Create a lightweight helper function that checks the file’s modification time (filemtime) on disk and appends it to the URL:
<?php
function asset(string $path): string {
$fullPath = __DIR__ . '/' . ltrim($path, '/');
$version = file_exists($fullPath) ? filemtime($fullPath) : 0;
return $path . '?v=' . $version;
}
Step 2: Usage in HTML/PHP Templates
<link rel="stylesheet" href="<?= asset('css/styles.css') ?>">
<script src="<?= asset('js/app.js') ?>" defer></script>
Rendered Output:
<link rel="stylesheet" href="css/styles.css?v=1795591200">
• When styles.css is untouched: The timestamp stays identical, so browsers serve the file from local disk.
• When you edit styles.css: The timestamp updates instantly, forcing browsers to download the fresh file.
Understanding Cache-Control: public, max-age=31536000, immutable
Simply adding ?v= isn’t enough if your web server doesn’t send the right HTTP caching headers. To get maximum speed, pair your versioned URLs with immutable.
What Each Directive Does
- public: Allows both the user’s browser and intermediate CDNs/proxies (like Cloudflare) to store the file.
- max-age=31536000: Tells the browser to keep the file cached for 1 full year (365 days in seconds).
- immutable: The secret weapon. Normally, when a user hits Refresh (F5), browsers ignore max-age and send a conditional request (If-Modified-Since) to your server for every CSS/JS/image file—resulting in dozens of 304 Not Modified round-trips. immutable promises the browser that this exact URL will never change, eliminating 304 validation requests completely on page reloads.
Nginx Configuration (No Rewrites Required)
You only want to apply immutable when ?v= is actually present in the URL (so unversioned files aren’t accidentally frozen for a year):
location ~* \.(css|js|png|jpg|jpeg|gif|webp|svg|woff2)$ {
# Apply 1-year immutable caching only when ?v= is present
if ($arg_v) {
add_header Cache-Control "public, max-age=31536000, immutable";
}
access_log off;
}
(Note: Using if ($arg_v) solely for add_header is completely safe in Nginx).
Going One Step Further: Filename Versioning (styles.1795591200.css)
While query strings work well on modern browsers and Cloudflare, some strict corporate proxies and legacy CDNs strip or ignore query strings (?v=). For advanced setups, you can spoof true filename hashing using Nginx without adding a build step.
Step 1: Update the PHP Helper
Inject the timestamp directly before the file extension:
<?php
function asset(string $path): string {
$fullPath = __DIR__ . '/' . ltrim($path, '/');
$version = file_exists($fullPath) ? filemtime($fullPath) : 0;
return preg_replace('{\\.([^./]+)$}', ".$version.\$1", $path);
}
Rendered Output: css/styles.1795591200.css
Step 2: Configure Nginx to Route It Back
You have two options in Nginx—choose based on how you want Nginx to handle file lookups:
Option A: Using try_files (Clean & Standard)
location ~* ^(.+)\.(\d+)\.(css|js|png|jpg|jpeg|gif|webp|svg|woff2)$ {
try_files $uri $1.$3 =404;
add_header Cache-Control "public, max-age=31536000, immutable";
access_log off;
}
Option B: Using rewrite … last (Skips Failed Disk Checks)
Because styles.1795591200.css does not physically exist on disk, try_files checks $uri first (cache miss) before falling back to $1.$3. Using rewrite … last jumps straight to the real file:
location ~* ^(.+)\.\d+\.(css|js|png|jpg|jpeg|gif|webp|svg|woff2)$ {
rewrite ^(.+)\.\d+\.(css|js|png|jpg|jpeg|gif|webp|svg|woff2)$ $1.$2 last;
}
Under the Hood: Resource Costs & Apache vs. Nginx Reality
A common hesitation among sysadmins with Apache backgrounds is avoiding rewrites due to performance penalties. Here is what actually happens under the hood:
- Why Apache Was Slow: Apache’s .htaccess model forced the server to traverse directories and read/parse regex rules from disk on every single HTTP request.
- Why Nginx Is Negligible: Nginx parses your configuration into RAM once at startup, compiling regex rules into a fast C state machine.
- The Real Cost (stat() calls): Both PHP’s filemtime() and Nginx’s try_files perform filesystem stat() checks. On modern NVMe VPS drives, a stat() call takes microseconds—and with proper RAM caching (below), the disk isn’t even touched after the first request.
Production Tuning: nginx.conf, php.ini, & PHP-FPM (8GB RAM VPS Blueprint)
If you are hosting 50+ PHP projects on a single 8GB RAM VPS, the real optimization isn’t choosing between ?v= and .timestamp.ext—it is keeping file metadata and compiled PHP code permanently in RAM.
A. Nginx File Descriptor Caching (/etc/nginx/nginx.conf)
Eliminates disk stat() overhead for try_files and static assets by storing open file descriptors and directory lookups in RAM:
http {
open_file_cache max=10000 inactive=60s;
open_file_cache_valid 120s;
open_file_cache_min_uses 1;
open_file_cache_errors on;
}
B. PHP Realpath & OPcache Tuning (/etc/php/8.x/fpm/php.ini)
By default, PHP’s realpath_cache_size is tiny (16K–4096K), causing filemtime() across 50 projects to constantly hit the disk. Increase it alongside OPcache so all 50 codebases stay compiled in RAM:
; Cache file paths & filemtime metadata in RAM
realpath_cache_size = 8192K
realpath_cache_ttl = 600
; Keep all 50+ PHP projects pre-compiled in RAM
opcache.enable = 1
opcache.memory_consumption = 512
opcache.interned_strings_buffer = 64
opcache.max_accelerated_files = 32531
opcache.validate_timestamps = 1
opcache.revalidate_freq = 2
C. Shared PHP-FPM Pool (/etc/php/8.x/fpm/pool.d/www.conf)
If you own all the projects on the server, avoid creating 50 separate PHP-FPM pools (which fragments RAM). Use one shared dynamic pool so all sites share warm worker processes:
pm = dynamic
pm.max_children = 40 ; ~40-50MB per worker = ~2GB max RAM
pm.start_servers = 8
pm.min_spare_servers = 4
pm.max_spare_servers = 12
pm.max_requests = 1000 ; Recycles workers to prevent memory leaks
Summary Decision Matrix
| Strategy | Best For | Pros | Cons |
|---|---|---|---|
?v=timestamp + immutable |
90% of single-VPS PHP setups & Cloudflare users | Zero Nginx rewrites; 2-minute setup; blocks 304 reload checks |
Some strict legacy proxies ignore query strings |
.timestamp.ext + Nginx rewrite |
Multi-CDN setups or strict proxy environments | 100% immune to query-string stripping; behaves like Webpack or Vite | Requires adding a regex location block in Nginx |
#php #nginx #devops #webperf #caching #sysadmin #WebPerformance #CacheBusting #ServerOptimization #BackendDevelopment #PageSpeed #OPcache #CacheControl #WebDev
Write a comment