Website Performance

Server-Side Caching with Nginx fastcgi_cache, Varnish and Redis

By NileVPS Team · Published · 5 min read

اقرأ المقال بالعربي

Application-level caching plugins are a good start, but the fastest response is one your application never has to produce. Server-side caching moves that work into the web server or a dedicated proxy, which can return a stored page in a fraction of the time it takes PHP to boot, load a framework and query a database. On a VPS you control the whole stack, so you can choose exactly where caching happens. This article covers the three tools you will meet most often: Nginx fastcgi_cache, Varnish and Redis, and explains when each one makes sense.

How server-side caching fits in

A typical PHP request on a VPS travels like this: visitor, Nginx, PHP-FPM, database, then back. Each tool caches at a different point:

ToolSits betweenCachesBest for
Nginx fastcgi_cacheNginx and PHP-FPMFull HTTP responses on disk (hot pages stay in the OS page cache)Most single-server PHP sites
VarnishVisitor and web serverFull HTTP responses in RAMComplex rules, high traffic, multiple backends
RedisApplication and databaseObjects, query results, sessionsDynamic and logged-in pages

Page caches (Nginx, Varnish) remove the application from the path for anonymous visitors. Redis speeds up the requests that still need the application. Most production sites use one page cache plus Redis. If you are new to the layers, our website caching guide gives the bigger picture.

Nginx fastcgi_cache step by step

If you already run Nginx with PHP-FPM, fastcgi_cache is the simplest server-level page cache because it adds no new service.

First, define a cache zone in the http context, for example in /etc/nginx/conf.d/fastcgi-cache.conf:

fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=SITE:100m inactive=60m max_size=1g;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

keys_zone=SITE:100m reserves shared memory for cache keys (one megabyte holds roughly eight thousand keys). max_size caps disk usage and inactive removes entries that nobody requested for an hour.

Next, decide which requests must skip the cache. Inside your server block:

set $skip_cache 0;
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
if ($request_uri ~* "/wp-admin/|/cart|/checkout|/my-account|/login") { set $skip_cache 1; }
if ($http_cookie ~* "wordpress_logged_in|woocommerce_items_in_cart|laravel_session") { set $skip_cache 1; }

Adjust the paths and cookie names to your application. Note that some frameworks set a session cookie for every visitor, which would disable caching for everyone; in that case match a login-specific cookie instead.

Then enable caching in the PHP location:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;

    fastcgi_cache SITE;
    fastcgi_cache_valid 200 301 10m;
    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;
}

Create the directory, test and reload:

sudo mkdir -p /var/cache/nginx/fastcgi
sudo nginx -t && sudo systemctl reload nginx
curl -sI https://yoursite.com/ | grep -i x-cache-status

The first request shows MISS, the second HIT. fastcgi_cache_lock lets only one request rebuild an expired page while others wait, and fastcgi_cache_use_stale serves the old copy if PHP fails, which keeps the site up during short backend problems.

To clear the cache completely, delete the directory contents and reload:

sudo find /var/cache/nginx/fastcgi -type f -delete

Purging single URLs requires the third-party ngx_cache_purge module or a plugin that understands the cache layout.

When Varnish is worth it

Varnish is a dedicated HTTP accelerator that keeps cached objects in memory and is configured with its own language, VCL. Because it is a separate service, the usual layout puts Nginx in front for TLS on port 443, Varnish behind it on port 6081 by default, and the web server or application behind Varnish on another port.

Varnish shines when you need:

  • Fine-grained rules written in VCL, such as normalising cookies or cache keys.
  • Purging and banning by URL pattern or tag through HTTP requests.
  • Grace mode to serve stale content while refreshing in the background.
  • Caching in front of several backends, not just PHP.

The trade-off is another service to monitor, more RAM, and more moving parts. For a single WordPress or Laravel site on one VPS, fastcgi_cache usually achieves most of the benefit with less complexity.

Redis for objects and sessions

Page caching does nothing for logged-in users, admin dashboards or carts. Redis covers those cases by storing data the application would otherwise recompute. Common uses:

  • Object cache: query results, configuration, rendered fragments.
  • Sessions: faster than file-based sessions and shared across processes.
  • Queues and rate limits: many frameworks use Redis for both.

Keep Redis local, set maxmemory and an eviction policy, and if you store sessions there, remember that eviction can log users out. Many teams use separate Redis databases or instances for cache and sessions, with noeviction on the session store.

Measuring the result

Check the response time from the first byte before and after:

curl -o /dev/null -s -w "TTFB: %{time_starttransfer}s\n" https://yoursite.com/

Also watch PHP-FPM load with top or htop during traffic. A working page cache shows lower CPU usage for the same traffic, and capacity you can use before needing a larger plan from our pricing page.

FAQ

Should I use Nginx fastcgi_cache or Varnish?

For most single-server PHP sites, start with fastcgi_cache: it needs no extra service and is easy to reason about. Choose Varnish when you need advanced VCL logic, tag-based purging, or a cache in front of several different backends.

Does server-side caching replace Redis?

No. A page cache serves complete pages to anonymous visitors, while Redis speeds up the application itself for requests that cannot be cached as whole pages, such as logged-in sessions and carts. They work best together.

Why does my cache always show MISS?

Usually a cookie or query string triggers your skip rules, or the application sends Cache-Control: private, no-cache or Set-Cookie headers, which Nginx respects by default. Inspect the response with curl -I, check which cookies are set, and adjust the bypass rules or headers accordingly.

Related guides