How to Configure Nginx FastCGI Cache for WordPress on an Ubuntu VPS Print

  • Nginx WordPress caching, Nginx cache purge, Ubuntu VPS WordPress, KVM VPS, Nginx cache HIT MISS BYPASS, Linux VPS, WordPress cache bypass, WordPress VPS hosting, WordPress performance optimization, FastCGI cache configuration, WooCommerce Nginx cache, FastCGI cache Ubuntu, Nginx FastCGI cache, WordPress TTFB optimization, WordPress FastCGI cache, Owned Networks, Nginx page cache, PHP-FPM caching, Nginx cache headers
  • 0

How to Configure Nginx FastCGI Cache for WordPress on an Ubuntu VPS

WordPress websites dynamically generate pages using PHP and database queries. While this provides flexibility, repeatedly generating identical pages for anonymous visitors can consume unnecessary CPU, memory, and database resources.

Nginx FastCGI Cache provides a server-level caching mechanism that stores eligible PHP-generated HTTP responses and serves subsequent requests directly from the cache.

By configuring FastCGI Cache correctly, you can significantly reduce PHP-FPM workload, improve Time to First Byte (TTFB), and increase the number of requests your VPS can handle.

In this tutorial, you will learn how to configure Nginx FastCGI Cache for WordPress on an Ubuntu VPS, including cache storage, cache keys, expiration policies, cache bypass rules, WooCommerce considerations, performance testing, and rollback procedures.

This guide is designed for Ubuntu 24.04 LTS, Ubuntu 26.04 LTS, and other supported Ubuntu releases running Nginx and PHP-FPM.

Prerequisites

  • An Ubuntu VPS with root or sudo access.
  • A working Nginx installation.
  • A functional WordPress website.
  • PHP-FPM configured and operational.
  • MariaDB or MySQL.
  • A domain name pointing to your VPS.
  • A working HTTPS configuration.
  • A verified backup of your website and Nginx configuration.
  • SSH or console access to the server.

This tutorial assumes a self-managed WordPress installation using a conventional Nginx virtual host.

If you use a hosting control panel that automatically generates Nginx configuration files, consult its documentation before making manual changes.

1. What Is Nginx FastCGI Cache?

Nginx FastCGI Cache stores responses received from a FastCGI application, such as PHP-FPM.

Without page caching, a typical WordPress request follows this process:

Visitor
   |
   v
Nginx
   |
   v
PHP-FPM
   |
   v
WordPress
   |
   v
MariaDB / MySQL
   |
   v
Generated HTTP Response

With FastCGI Cache enabled, eligible requests can follow a much shorter path:

Visitor
   |
   v
Nginx
   |
   v
FastCGI Cache
   |
   v
Cached HTTP Response

When a valid cached response exists, Nginx can serve it without executing WordPress or contacting the database for that request.

This can provide substantial performance improvements for websites receiving repeated requests for public content.

2. FastCGI Cache vs. Redis and Memcached

FastCGI Cache, Redis, and Memcached operate at different layers of the application stack.

Technology Cache Type Primary Purpose
Nginx FastCGI Cache Full-page HTTP response cache Avoid repeated PHP and database processing
Redis Persistent object cache Reduce repeated database queries and application computations
Memcached Memory-based object cache Store frequently accessed temporary application data
PHP OPcache PHP bytecode cache Reduce PHP script compilation overhead
CDN Distributed content cache Deliver eligible content closer to visitors

FastCGI Cache can work alongside PHP OPcache and either Redis or Memcached.

These technologies complement each other because they optimize different stages of request processing.

3. When Should You Use FastCGI Cache?

FastCGI Cache is particularly useful for:

  • WordPress blogs.
  • Corporate websites.
  • News websites.
  • Content publishing platforms.
  • Landing pages.
  • Documentation websites.
  • Public product catalog pages.
  • Websites experiencing high anonymous visitor traffic.

Additional precautions are necessary for:

  • WooCommerce stores.
  • Membership websites.
  • Learning management systems.
  • Customer portals.
  • Websites displaying personalized content.
  • Applications using authentication cookies or sessions.

Security warning: Incorrectly configured full-page caching can expose private or customer-specific information to other visitors.

Always test the cache policy against your actual application behavior before enabling it in production.

4. Check the Existing Nginx and PHP Configuration

Check the installed Nginx version:

nginx -v

Inspect the compiled Nginx modules:

nginx -V 2>&1

Check the PHP version:

php -v

Identify the active PHP-FPM services:

systemctl list-units --type=service | grep php

List the available PHP-FPM sockets:

ls -lah /run/php/

For example:

/run/php/php8.3-fpm.sock

Your server may use a different PHP version or a dedicated PHP-FPM pool socket.

Always use the socket configured for your actual WordPress website.

Review the complete active Nginx configuration:

sudo nginx -T

Check whether FastCGI Cache is already configured:

sudo nginx -T 2>&1 | grep -E 'fastcgi_cache|fastcgi_no_cache'

If an existing cache configuration is present, review it before adding new directives.

5. Back Up the Existing Nginx Configuration

Before making changes, create a timestamped backup of the Nginx configuration.

BACKUP="/root/nginx-backup-$(date +%Y%m%d-%H%M%S)"

sudo mkdir -p "$BACKUP"

sudo cp -a /etc/nginx/. "$BACKUP/"

echo "Nginx backup: $BACKUP"

Record the backup directory displayed by the command.

Validate the current configuration:

sudo nginx -t

Do not proceed until the existing Nginx configuration passes validation.

6. Measure Website Performance Before Enabling Cache

Establish a baseline before making configuration changes.

Replace example.com with your actual WordPress domain.

curl -s -o /dev/null \
-w 'HTTP: %{http_code}\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n' \
https://example.com/

Run several requests:

for i in $(seq 1 5); do
    curl -s -o /dev/null \
    -w 'HTTP: %{http_code} TTFB: %{time_starttransfer}s Total: %{time_total}s\n' \
    https://example.com/
done

Record the results for comparison after enabling FastCGI Cache.

If your website uses a CDN or reverse proxy, the measured response time may include additional network and caching layers.

7. Create the FastCGI Cache Directory

Create a dedicated directory for WordPress FastCGI Cache:

sudo mkdir -p /var/cache/nginx/wordpress

On a standard Ubuntu Nginx installation, the worker processes commonly run as www-data.

Verify the configured Nginx user:

grep -E '^user ' /etc/nginx/nginx.conf

If Nginx runs as www-data, configure ownership and permissions:

sudo chown www-data:www-data /var/cache/nginx/wordpress

sudo chmod 750 /var/cache/nginx/wordpress

Check available disk space:

df -h /var/cache/nginx/wordpress

FastCGI Cache stores response bodies on disk and maintains cache metadata in shared memory.

It does not store the entire cache exclusively in RAM.

8. Configure the Global FastCGI Cache Zone

Create a dedicated Nginx configuration file:

sudo nano /etc/nginx/conf.d/wordpress-fastcgi-cache.conf

Add the following configuration:

fastcgi_cache_path /var/cache/nginx/wordpress
    levels=1:2
    keys_zone=WORDPRESS:32m
    inactive=60m
    max_size=1g
    use_temp_path=off;

The fastcgi_cache_path directive must be placed inside the Nginx HTTP configuration context.

On standard Ubuntu installations, files under /etc/nginx/conf.d/ are normally included within that context.

Verify the include configuration if your installation differs.

9. Understand the FastCGI Cache Parameters

Parameter Example Description
Cache directory /var/cache/nginx/wordpress Location where cached responses are stored
levels 1:2 Directory hierarchy used for cached files
keys_zone WORDPRESS:32m Shared memory zone for cache metadata
inactive 60m Remove cached items that have not been accessed for this period
max_size 1g Target maximum disk usage managed by the cache manager
use_temp_path off Store temporary cache files in the cache directory

The inactive setting is different from the cache validity period.

An inactive cache entry can be removed even if its response has not expired.

The max_size setting is managed asynchronously and should not be treated as an absolute instantaneous disk usage limit.

For smaller VPS servers, consider reducing the cache metadata zone and maximum disk usage according to available resources.

10. Configure Safe Cache Bypass Rules

Not every WordPress request should be cached.

Requests involving authentication, cookies, administration pages, shopping carts, API endpoints, or personalized content must be handled carefully.

For this tutorial, we will use a conservative policy that only permits eligible public requests without cookies, authorization headers, or query strings.

Open the global cache configuration file:

sudo nano /etc/nginx/conf.d/wordpress-fastcgi-cache.conf

Keep the existing fastcgi_cache_path directive and append the following configuration:

map $request_method $wp_skip_method {
    default 1;
    GET     0;
    HEAD    0;
}

map $args $wp_skip_query {
    default 1;
    ""      0;
}

map $http_cookie $wp_skip_cookie {
    default 1;
    ""      0;
}

map $http_authorization $wp_skip_auth {
    default 1;
    ""      0;
}

map $request_uri $wp_skip_uri {
    default 0;

    ~*^/wp-admin(?:/|$)         1;
    ~*^/wp-login\.php           1;
    ~*^/wp-register\.php        1;
    ~*^/wp-cron\.php            1;
    ~*^/xmlrpc\.php             1;
    ~*^/wp-json(?:/|$)          1;
    ~*^/wp-comments-post\.php   1;
    ~*^/wp-signup\.php          1;
    ~*^/wp-activate\.php        1;

    ~*^/cart(?:/|$)             1;
    ~*^/checkout(?:/|$)         1;
    ~*^/my-account(?:/|$)       1;
    ~*^/wc-api(?:/|$)           1;

    ~*^/feed(?:/|$)             1;
    ~*^/index\.php(?:/|$)       1;
}

map "$wp_skip_method:$wp_skip_query:$wp_skip_cookie:$wp_skip_auth:$wp_skip_uri" $wp_skip_cache {
    default     1;
    "0:0:0:0:0" 0;
}

These rules bypass caching for:

  • HTTP methods other than GET and HEAD.
  • Requests containing query strings.
  • Requests containing cookies.
  • Requests containing authorization headers.
  • WordPress administrative and authentication endpoints.
  • Common WordPress API endpoints.
  • Common WooCommerce cart, checkout, and account pages.

Important: Bypassing all requests containing cookies is deliberately conservative.

This can reduce the cache hit ratio for websites using analytics, consent, language, or other non-authentication cookies.

However, it provides a safer starting point than assuming that only a predefined list of authentication cookies affects personalized content.

Applications using custom endpoints, header-based personalization, geolocation, or other mechanisms may require additional exclusions.

11. Prevent Caching of Responses That Set Cookies

Some requests may create a new application session even when the visitor did not originally send a cookie.

Append the following response-based map to the global configuration file:

map $upstream_http_set_cookie $wp_response_sets_cookie {
    default 1;
    ""      0;
}

We will use this variable to prevent eligible requests from storing responses that create cookies.

Nginx normally respects upstream Set-Cookie, Cache-Control, and other cache-related response headers.

Do not configure Nginx to ignore these headers simply to increase the cache hit ratio.

In particular, avoid directives such as:

fastcgi_ignore_headers Set-Cookie Cache-Control;

Ignoring these headers can cause personalized or explicitly non-cacheable content to be stored in a shared cache.

12. Configure the WordPress Virtual Host

Identify your active WordPress virtual host:

ls -lah /etc/nginx/sites-enabled/

For example:

/etc/nginx/sites-available/example.com

Open the corresponding configuration file:

sudo nano /etc/nginx/sites-available/example.com

Locate the PHP location block within the HTTPS server configuration.

A typical PHP-FPM configuration may look like:

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

Do not replace the complete virtual host unnecessarily.

Preserve existing SSL settings, security restrictions, WordPress routing, PHP-FPM parameters, and application-specific configuration.

Modify the existing PHP location block to include the FastCGI Cache directives shown in the next section.

13. Enable FastCGI Cache in the PHP Location Block

For a conventional Ubuntu WordPress installation, the resulting PHP location block may look like:

location ~ \.php$ {

    include snippets/fastcgi-php.conf;

    fastcgi_pass unix:/run/php/php8.3-fpm.sock;

    fastcgi_cache WORDPRESS;

    fastcgi_cache_key "$scheme|$host|$request_uri";

    fastcgi_cache_methods GET HEAD;

    fastcgi_cache_valid 200 10m;

    fastcgi_cache_min_uses 1;

    fastcgi_cache_bypass $wp_skip_cache;

    fastcgi_no_cache $wp_skip_cache
                     $wp_response_sets_cookie;

    fastcgi_cache_lock on;

    fastcgi_cache_lock_timeout 5s;

    fastcgi_cache_lock_age 5s;

    add_header X-FastCGI-Cache $upstream_cache_status always;
}

Replace the PHP-FPM socket with the correct socket for your installation.

Important: If your existing PHP location block contains additional security directives, preserve them.

Also ensure that adding the diagnostic response header does not unintentionally remove inherited security headers. Nginx header inheritance behavior depends on the configuration and installed version.

Inspect the final HTTP response headers after applying the configuration.

14. Understand the Cache Key

The following directive determines how cached responses are identified:

fastcgi_cache_key "$scheme|$host|$request_uri";

This separates cached responses according to:

  • HTTP or HTTPS scheme.
  • Requested hostname.
  • Original request URI.

Including the hostname helps prevent cache collisions between websites sharing the same cache zone.

Including the original request URI ensures that different WordPress permalink paths use separate cache entries.

GET and HEAD requests can share the same cache entry when the normal Nginx HEAD-to-GET cache conversion behavior is enabled.

For applications serving different content based on additional request properties, the cache key or bypass policy may require further customization.

15. Understand Cache Expiration

The following directive configures a default cache validity period for successful HTTP 200 responses:

fastcgi_cache_valid 200 10m;

This means that eligible successful responses can normally remain valid for ten minutes, subject to upstream response headers and other cache controls.

For frequently updated websites, a shorter validity period may be appropriate.

For example:

fastcgi_cache_valid 200 2m;

For relatively static public websites, a longer validity period may be appropriate:

fastcgi_cache_valid 200 30m;

Choose a validity period according to how frequently content changes and whether automatic cache invalidation is available.

Important: WordPress content updates do not automatically invalidate Nginx FastCGI Cache unless a compatible cache invalidation mechanism has been configured.

16. Prevent Cache Stampedes

A cache stampede occurs when multiple requests simultaneously attempt to regenerate the same expired or missing cached response.

This can cause unnecessary PHP-FPM and database load.

The following directive enables cache locking:

fastcgi_cache_lock on;

Cache locking allows one request to populate a missing cache entry while other eligible requests wait, subject to the configured lock behavior.

The following settings control the waiting and lock age limits:

fastcgi_cache_lock_timeout 5s;
fastcgi_cache_lock_age 5s;

This can be particularly useful during traffic spikes or when popular cache entries expire.

17. Optional: Serve Stale Cached Content During Origin Errors

Nginx can optionally serve an expired cached response when PHP-FPM encounters certain errors.

For a public content website, you may consider adding:

fastcgi_cache_use_stale error
                        timeout
                        invalid_header
                        updating
                        http_500
                        http_503;

You may also enable background cache updates:

fastcgi_cache_background_update on;

These features can improve availability during temporary backend problems and reduce the impact of cache expiration.

However, stale content may be inappropriate for websites displaying time-sensitive information, inventory availability, pricing, or other frequently changing data.

These settings are optional and are not included in the default configuration provided by this tutorial.

18. Validate and Reload Nginx

Before applying the configuration, validate its syntax:

sudo nginx -t

Expected output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If validation fails, do not reload Nginx.

Review the reported configuration file and line number, then correct the problem.

Once validation succeeds, reload Nginx:

sudo systemctl reload nginx

Verify service status:

sudo systemctl status nginx --no-pager

Review recent service logs:

sudo journalctl -u nginx -n 50 --no-pager

A successful Nginx reload normally applies the configuration without terminating established connections abruptly.

19. Verify That FastCGI Cache Is Working

Request a public WordPress page without cookies or authentication headers:

curl -sS -D - -o /dev/null https://example.com/

Look for the diagnostic response header:

X-FastCGI-Cache: MISS

Repeat the request:

curl -sS -D - -o /dev/null https://example.com/

If the response is eligible for caching, you should normally see:

X-FastCGI-Cache: HIT

Run several consecutive requests:

for i in $(seq 1 5); do
    echo "Request $i"
    curl -sS -D - -o /dev/null https://example.com/ |
        grep -i '^X-FastCGI-Cache:'
    sleep 1
done

The first request may return MISS, followed by subsequent requests returning HIT.

If the application sends headers that prevent caching, repeated requests may continue to return MISS.

20. Understand FastCGI Cache Status Values

Status Meaning
MISS No usable cached response was found
HIT A valid cached response was served
BYPASS The request was intentionally excluded from cache retrieval
EXPIRED A cached response existed but had expired
STALE An expired cached response was served under configured stale-response conditions
UPDATING A stale response was served while another request updated the cache
REVALIDATED An expired cached response was successfully revalidated

Not every status will appear with the default configuration.

Some statuses require additional cache revalidation or stale-response settings.

21. Test Cache Bypass Rules

After confirming that public pages can produce cache hits, verify that excluded requests are not served from the cache.

Test a Request Containing a Cookie

curl -sS -D - -o /dev/null \
-H 'Cookie: cache_test=1' \
https://example.com/

Expected cache status for a request handled by PHP:

X-FastCGI-Cache: BYPASS

Test a Request Containing a Query String

curl -sS -D - -o /dev/null \
'https://example.com/?cache_test=1'

Expected:

X-FastCGI-Cache: BYPASS

Test the WordPress Login Page

curl -sS -D - -o /dev/null \
https://example.com/wp-login.php

Expected:

X-FastCGI-Cache: BYPASS

Test the WordPress REST API

curl -sS -D - -o /dev/null \
https://example.com/wp-json/

Expected:

X-FastCGI-Cache: BYPASS

Test a Request Containing an Authorization Header

curl -sS -D - -o /dev/null \
-H 'Authorization: Bearer cache-test' \
https://example.com/

The request must not be served as a shared FastCGI Cache hit.

Note: Requests handled directly by Nginx, redirected before reaching PHP, or rejected by another security layer may not include the FastCGI Cache diagnostic header.

The absence of a header in those situations does not necessarily indicate a caching problem.

22. Configure FastCGI Cache Safely for WooCommerce

WooCommerce websites require additional precautions because customer sessions, shopping carts, checkout pages, and account information must not be publicly cached.

The default configuration in this tutorial bypasses all requests containing cookies and query strings.

It also excludes common WooCommerce paths:

/cart/
/checkout/
/my-account/
/wc-api/

However, WooCommerce page URLs can be customized or translated.

For example, a Spanish-language WooCommerce installation may use:

/carrito/
/finalizar-compra/
/mi-cuenta/

If your store uses these paths, add the corresponding exclusions to the $wp_skip_uri map:

~*^/carrito(?:/|$)             1;
~*^/finalizar-compra(?:/|$)     1;
~*^/mi-cuenta(?:/|$)           1;

Check the actual URLs configured in your WooCommerce installation.

Also review any additional customer portals, payment endpoints, membership pages, subscription management pages, or custom application routes.

After making changes:

sudo nginx -t && sudo systemctl reload nginx

23. Test the Complete WooCommerce Purchasing Workflow

Do not consider a WooCommerce cache configuration production-ready until the complete purchasing workflow has been tested.

Use two independent browser profiles or private browsing sessions.

Verify that:

  • Anonymous visitors can browse public products.
  • Adding products to a cart works correctly.
  • Each visitor sees only their own shopping cart.
  • Cart quantities update correctly.
  • Coupons are applied to the correct session.
  • Checkout displays the correct customer information.
  • Customer account pages are not shared between sessions.
  • Payment integrations function correctly.
  • Order confirmation pages are not publicly cached.
  • Logging in and out does not expose another user's information.

Use a staging environment or payment gateway test mode when validating checkout behavior.

Security warning: If any personalized response is served from a shared cache, disable the affected caching layer immediately and investigate before re-enabling it.

24. Optional: Improve the Cache Hit Ratio Using Cookie Exclusions

The default configuration bypasses all requests containing cookies.

While conservative, this may prevent caching for visitors who only have analytics or consent cookies.

After reviewing the application's cookie behavior, an administrator may choose to replace the all-cookie bypass map with a more selective policy.

Common WordPress and WooCommerce session-related cookie patterns include:

wordpress_logged_in_
wordpress_sec_
wp-postpass_
comment_author_
woocommerce_items_in_cart
woocommerce_cart_hash
wp_woocommerce_session_
PHPSESSID

A selective cookie bypass map might resemble:

map $http_cookie $wp_skip_cookie {
    default 0;

    ~*wordpress_logged_in_        1;
    ~*wordpress_sec_              1;
    ~*wp-postpass_                1;
    ~*comment_author_             1;
    ~*woocommerce_items_in_cart   1;
    ~*woocommerce_cart_hash       1;
    ~*wp_woocommerce_session_     1;
    ~*PHPSESSID                   1;
}

Warning: This is an illustrative optimization, not a universally safe replacement for the default policy.

Plugins, themes, membership systems, multilingual websites, currency switchers, and custom applications may introduce additional cookies that affect response content.

Only implement selective cookie caching after auditing those dependencies and testing multiple independent user sessions.

For maximum safety, retain the default all-cookie bypass policy unless there is a demonstrated need to change it.

25. Configure WordPress Cache Invalidation

FastCGI Cache operates independently of WordPress.

When a WordPress administrator publishes or updates a page, Nginx does not automatically know that the corresponding cached response should be removed.

There are several approaches to cache invalidation:

  • Use short cache validity periods.
  • Manually clear the cache after important updates.
  • Use a maintained WordPress integration compatible with your Nginx cache implementation.
  • Implement controlled cache invalidation through an administrative service.
  • Use a supported Nginx cache purge module or commercial cache purge functionality.

Standard open-source Nginx installations do not necessarily include an HTTP FastCGI cache purge capability.

Do not assume that installing a WordPress cache plugin automatically provides the required Nginx purge functionality.

Verify compatibility between the plugin, installed Nginx modules, filesystem permissions, and cache invalidation mechanism.

Security warning: Never expose an unrestricted public cache purge endpoint.

Unauthorized cache invalidation can increase origin workload and potentially contribute to denial-of-service conditions.

26. Manually Clear the FastCGI Cache

For a small WordPress website, manually clearing cached responses may be sufficient after important content updates.

First, verify the configured cache directory:

sudo nginx -T 2>&1 | grep fastcgi_cache_path

Check its current disk usage:

sudo du -sh /var/cache/nginx/wordpress

Preview the number of cached files:

sudo find /var/cache/nginx/wordpress -type f | wc -l

To remove cached files while preserving the directory structure:

sudo find /var/cache/nginx/wordpress \
    -xdev -type f -delete

Only execute this command after confirming that the directory is exclusively dedicated to disposable FastCGI Cache data.

Do not substitute a WordPress installation directory or another application data directory.

Verify the cache directory:

sudo du -sh /var/cache/nginx/wordpress

Request a public page again:

curl -sS -D - -o /dev/null https://example.com/ |
    grep -i '^X-FastCGI-Cache:'

The next eligible request should normally produce a cache miss, followed by a cache hit on subsequent requests.

Important: Requests may repopulate the cache while files are being removed. A live directory cleanup is not an atomic invalidation operation.

For strict invalidation requirements, use a supported purge mechanism or a controlled cache-generation rotation procedure.

27. Test FastCGI Cache Behind Cloudflare or Another CDN

If your WordPress website uses Cloudflare or another CDN, an external request may be served by the CDN rather than reaching Nginx.

This can make it difficult to determine whether FastCGI Cache is functioning correctly at the origin.

Inspect the response headers:

curl -sS -D - -o /dev/null https://example.com/

Cloudflare may return headers such as:

CF-Cache-Status: HIT

And your origin may return:

X-FastCGI-Cache: HIT

These headers refer to different caching layers.

To test the origin directly from the VPS, while preserving the correct hostname and TLS Server Name Indication, use:

curl -sS \
    --resolve example.com:443:127.0.0.1 \
    -D - -o /dev/null \
    https://example.com/

This assumes Nginx accepts HTTPS connections on the loopback address.

If necessary, replace 127.0.0.1 with the appropriate origin IP address.

The origin must present a certificate trusted by the testing client.

If the origin uses a private certificate authority, configure the appropriate CA certificate rather than routinely disabling TLS verification.

Do not weaken firewall restrictions or expose a protected origin merely to perform a cache test.

28. Measure Performance After Enabling FastCGI Cache

Repeat the baseline performance test:

for i in $(seq 1 10); do
    curl -s -o /dev/null \
    -w 'HTTP: %{http_code} TTFB: %{time_starttransfer}s Total: %{time_total}s\n' \
    https://example.com/
done

For a more informative comparison, display both timing and cache status:

for i in $(seq 1 5); do
    echo "Request $i"

    curl -sS -D - -o /dev/null \
        -w 'TTFB: %{time_starttransfer}s Total: %{time_total}s\n' \
        https://example.com/ |
        grep -Ei '^(HTTP/|X-FastCGI-Cache:|TTFB:)'

    sleep 1
done

Example results:

Request 1
HTTP/2 200
X-FastCGI-Cache: MISS
TTFB: 0.420s Total: 0.435s

Request 2
HTTP/2 200
X-FastCGI-Cache: HIT
TTFB: 0.035s Total: 0.041s

These results are illustrative and are not guaranteed performance figures.

Actual performance depends on network latency, application complexity, cache eligibility, server resources, and other infrastructure components.

29. Monitor FastCGI Cache Disk Usage

FastCGI Cache stores cached response bodies on disk.

Monitor the cache directory periodically:

sudo du -sh /var/cache/nginx/wordpress

Check the number of cached files:

sudo find /var/cache/nginx/wordpress -type f | wc -l

Check available filesystem capacity:

df -h /var/cache/nginx/wordpress

Check inode availability:

df -i /var/cache/nginx/wordpress

Large caches can consume significant disk space and filesystem inodes.

Configure the cache size according to your VPS storage capacity and application requirements.

30. Add Cache Status to Nginx Access Logs

Logging FastCGI Cache status allows you to evaluate cache effectiveness over time.

Create a dedicated logging configuration:

sudo nano /etc/nginx/conf.d/wordpress-cache-logging.conf

Add:

log_format wordpress_cache
    '$remote_addr [$time_local] '
    '"$request_method $uri $server_protocol" '
    '$status $body_bytes_sent '
    'rt=$request_time '
    'urt=$upstream_response_time '
    'cache=$upstream_cache_status';

The log_format directive must be placed inside the HTTP configuration context.

Next, add a dedicated access log directive to the appropriate WordPress server block:

access_log /var/log/nginx/wordpress-cache-access.log wordpress_cache;

If your virtual host already uses an access log, decide whether to retain both logs or replace the existing logging directive.

Validate and reload Nginx:

sudo nginx -t && sudo systemctl reload nginx

Monitor the log:

sudo tail -f /var/log/nginx/wordpress-cache-access.log

Example:

192.0.2.10 [10/Jan/2026:12:00:00 +0000] "GET / HTTP/2.0" 200 12500 rt=0.002 urt=- cache=HIT

Ensure the additional log is covered by your log rotation policy.

Access logs may contain personal data and should be retained and protected according to your organization's privacy and security requirements.

31. Calculate the FastCGI Cache Hit Ratio

Summarize cache status values from the dedicated access log:

sudo awk '
{
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^cache=/) {
            split($i, a, "=");
            if (a[2] != "-") count[a[2]]++;
        }
    }
}
END {
    for (status in count)
        printf "%-12s %d\n", status, count[status];
}' /var/log/nginx/wordpress-cache-access.log

Example output:

HIT          8500
MISS         900
BYPASS       1200
EXPIRED      100

To calculate a simplified cache hit ratio for requests not explicitly bypassed:

sudo awk '
{
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^cache=/) {
            split($i, a, "=");

            if (a[2] == "HIT")
                hits++;

            if (a[2] != "-" && a[2] != "BYPASS" && a[2] != "")
                total++;
        }
    }
}
END {
    if (total > 0)
        printf "Cache hit ratio: %.2f%% (%d/%d)\n",
               (hits / total) * 100, hits, total;
    else
        print "No applicable cache requests found.";
}' /var/log/nginx/wordpress-cache-access.log

This simplified calculation counts only fresh cache hits as hits and excludes explicitly bypassed requests.

Other cache effectiveness metrics may also count stale or revalidated responses separately.

A high cache hit ratio is useful, but it must never take priority over application correctness or user privacy.

32. Monitor PHP-FPM and Server Resource Usage

After enabling FastCGI Cache, monitor the impact on your VPS.

Check CPU and memory utilization:

top

Check available memory:

free -h

Inspect PHP-FPM processes:

ps -eo pid,user,%cpu,%mem,rss,args |
    grep '[p]hp-fpm'

Check system load:

uptime

For disk performance monitoring:

sudo apt install -y sysstat

iostat -xz 1

FastCGI Cache can reduce PHP and database workload for eligible requests, but uncached and authenticated requests still require application processing.

For additional monitoring instructions, see our Linux VPS resource monitoring tutorial.

33. Recommended FastCGI Cache Starting Values

The following values are illustrative starting points for different VPS resource profiles.

VPS RAM Cache Metadata Zone Cache Disk Size Default Validity
1 GB 8 MB 256 MB 5 minutes
2 GB 16 MB 512 MB 5-10 minutes
4 GB 32 MB 1 GB 10 minutes
8 GB 64 MB 2 GB 10-30 minutes
16 GB or more 64-128 MB 2-5 GB Application-dependent

These are not mandatory settings or benchmark-derived recommendations.

Cache sizing should primarily depend on the number of unique cacheable URLs, average response size, available storage, traffic patterns, and content update frequency.

A large VPS hosting a small website may require only a modest cache.

34. Troubleshooting Common FastCGI Cache Problems

Every Request Returns MISS

Inspect the complete response headers:

curl -sS -D - -o /dev/null https://example.com/

Look for headers such as:

Set-Cookie:
Cache-Control:
Expires:
Vary:
X-Accel-Expires:

WordPress or one of its plugins may intentionally prevent the response from being cached.

Check cache directory permissions:

sudo ls -ld /var/cache/nginx/wordpress

Review Nginx errors:

sudo tail -n 100 /var/log/nginx/error.log

Do not ignore application cache-control headers merely to force cache hits.

Every Request Returns BYPASS

Check whether the request includes:

  • Cookies.
  • Query strings.
  • Authorization headers.
  • An excluded URL.
  • An unsupported HTTP method.

Test a clean public request using curl without cookies or query strings.

The X-FastCGI-Cache Header Is Missing

Verify that the diagnostic header is configured in the active PHP location block.

sudo nginx -T 2>&1 |
    grep -E 'fastcgi_cache|X-FastCGI-Cache'

The request may also be served directly by Nginx as a static file, handled by another location block, or answered by a CDN.

Nginx Reports an Unknown Cache Zone

An error similar to the following may appear:

"fastcgi_cache" zone "WORDPRESS" is unknown

Verify that the global configuration contains:

keys_zone=WORDPRESS:32m

And that the PHP location block references the same zone:

fastcgi_cache WORDPRESS;

Also confirm that the global configuration file is included inside the Nginx HTTP context.

Nginx Reports a Duplicate Cache Zone

Check whether the cache zone is defined more than once:

sudo nginx -T 2>&1 | grep keys_zone

Review the configuration files for duplicate cache path or zone definitions.

WordPress Updates Are Not Immediately Visible

The previous response may remain cached until its validity period expires.

Clear the relevant cache using your configured invalidation mechanism or wait for expiration.

Consider reducing the cache validity period for frequently updated content.

WooCommerce Cart or Account Pages Display Incorrect Content

Immediately disable FastCGI Cache for the affected website.

Review all application routes, session cookies, authentication mechanisms, and CDN caching rules.

Clear affected cached responses and verify the website using multiple independent browser sessions.

If private information may have been exposed, investigate the incident according to your organization's security and privacy procedures.

FastCGI Cache Is Consuming Too Much Disk Space

Check the configured maximum cache size:

sudo nginx -T 2>&1 | grep -A 5 fastcgi_cache_path

Review disk usage:

sudo du -sh /var/cache/nginx/wordpress

df -h

df -i

Reduce the configured cache size or inactive period if appropriate.

Remember that cache size management occurs asynchronously.

35. Temporarily Disable FastCGI Cache

If FastCGI Cache causes unexpected behavior, it can be disabled without uninstalling Nginx or PHP-FPM.

Open the affected WordPress virtual host:

sudo nano /etc/nginx/sites-available/example.com

Replace:

fastcgi_cache WORDPRESS;

With:

fastcgi_cache off;

Validate the configuration:

sudo nginx -t

Reload Nginx if validation succeeds:

sudo systemctl reload nginx

Verify that the affected website no longer serves FastCGI Cache hits.

The cache files may remain on disk until removed manually or cleaned by the cache manager.

If the cache is being disabled because of a suspected privacy issue, clear the affected cached content before re-enabling caching.

36. Roll Back the Nginx Configuration

If you need to restore the original configuration, locate the timestamped backup created earlier:

sudo ls -ld /root/nginx-backup-*

Identify the correct backup directory and set its path:

BACKUP="/root/nginx-backup-YYYYMMDD-HHMMSS"

Replace the example timestamp with your actual backup directory.

Verify that the original virtual host exists in the backup:

sudo ls -l "$BACKUP/sites-available/example.com"

Restore the original virtual host:

sudo cp -a \
    "$BACKUP/sites-available/example.com" \
    /etc/nginx/sites-available/example.com

If the global FastCGI Cache configuration file was newly created exclusively for this tutorial, remove it:

sudo rm -f /etc/nginx/conf.d/wordpress-fastcgi-cache.conf

If the dedicated cache logging configuration was also newly created exclusively for this tutorial, remove it:

sudo rm -f /etc/nginx/conf.d/wordpress-cache-logging.conf

Important: If either configuration file existed before this tutorial, restore its original version from the backup instead of deleting it.

If multiple websites have subsequently been configured to use the cache zone or logging format, remove their dependencies before deleting the global configuration files.

Validate the restored configuration:

sudo nginx -t

Only reload Nginx after successful validation:

sudo systemctl reload nginx

Verify service status:

sudo systemctl status nginx --no-pager

Finally, test the website:

curl -I https://example.com/

Verify WordPress login, administration, public pages, and any application-specific functionality.

37. FastCGI Cache Security Best Practices

  • Never cache authenticated customer-specific responses.
  • Use conservative cache bypass rules initially.
  • Exclude administrative and authentication endpoints.
  • Exclude shopping carts, checkout pages, and account pages.
  • Respect upstream cache-control and cookie headers.
  • Do not expose unrestricted cache purge endpoints.
  • Restrict access to the cache directory.
  • Keep Nginx, PHP, WordPress, and plugins updated.
  • Audit custom application routes and session mechanisms.
  • Test caching using independent browser sessions.
  • Review CDN caching rules separately.
  • Maintain timestamped configuration backups.
  • Monitor disk usage and cache effectiveness.
  • Disable caching immediately if personalized content is incorrectly shared.

38. Recommended WordPress Performance Stack

A properly configured WordPress VPS may use the following architecture:

Visitors
    |
    v
CDN / Reverse Proxy (Optional)
    |
    v
Nginx
    |
    +-- FastCGI Cache HIT
    |       |
    |       +-- Cached Response
    |
    +-- MISS / BYPASS
            |
            v
         PHP-FPM
            |
         PHP OPcache
            |
            v
         WordPress
            |
            +-- Redis or Memcached
            |
            +-- MariaDB / MySQL

This architecture combines full-page caching, PHP bytecode caching, persistent object caching, and database optimization.

Each component should be configured according to the application's requirements and available VPS resources.

39. Final Verification Checklist

Before considering the FastCGI Cache deployment complete, verify the following:

  • Nginx configuration passes syntax validation.
  • Nginx and PHP-FPM are operational.
  • Public anonymous pages can produce cache hits.
  • Requests containing authentication headers bypass the cache.
  • Requests containing cookies follow the intended cache policy.
  • WordPress login and administration pages are not cached.
  • WooCommerce customer-specific pages are excluded.
  • Application-generated private responses are not cached.
  • Cache invalidation behavior is understood and documented.
  • Disk usage remains within acceptable limits.
  • Cache status logging is operational if configured.
  • Performance has been measured before and after deployment.
  • A verified rollback procedure remains available.

Related WordPress and Ubuntu VPS Tutorials

Frequently Asked Questions

Does Nginx FastCGI Cache Require a WordPress Plugin?

No. Nginx FastCGI Cache operates at the web server level and can cache eligible WordPress responses without requiring a WordPress plugin.

However, a compatible integration may be useful for automatic cache invalidation when WordPress content changes.

Can I Use FastCGI Cache and Redis Together?

Yes. FastCGI Cache stores complete eligible HTTP responses, while Redis can store reusable WordPress application objects.

They operate at different layers and can complement each other.

Does FastCGI Cache Work with WooCommerce?

Yes, provided the cache configuration correctly excludes personalized responses, customer sessions, shopping carts, checkout pages, account pages, and other dynamic application functionality.

Comprehensive testing is required before enabling it in a production WooCommerce store.

Does FastCGI Cache Improve WordPress TTFB?

FastCGI Cache can significantly improve server response times for eligible cached requests because Nginx does not need to execute PHP or query the database for each cache hit.

The actual improvement depends on the website, server resources, network latency, and cache effectiveness.

Does FastCGI Cache Store Everything in RAM?

No. Nginx normally stores cached response bodies on disk and maintains cache metadata in a shared memory zone.

Can FastCGI Cache Be Used Behind Cloudflare?

Yes. Cloudflare and Nginx FastCGI Cache can operate as separate caching layers.

Both layers must be configured to respect authentication, personalized content, and application-specific cache exclusions.

Do I Need to Restart Nginx After Changing Cache Settings?

In most cases, validating the configuration and gracefully reloading Nginx is sufficient.

sudo nginx -t && sudo systemctl reload nginx

Why Does My FastCGI Cache Always Return MISS?

The application may return headers that prevent caching, the cache directory may have incorrect permissions, or the response may not satisfy the configured caching policy.

Inspect response headers and Nginx logs before modifying cache restrictions.

Deploy High-Performance WordPress Websites with Owned Networks

Optimizing WordPress at the server level can reduce unnecessary resource consumption and improve website responsiveness.

With Owned Networks KVM VPS hosting, you have full root access and the flexibility to configure Nginx, PHP-FPM, FastCGI Cache, Redis, Memcached, MariaDB, and other performance technologies according to your application requirements.

Whether you manage a WordPress blog, corporate website, publishing platform, or WooCommerce store, a properly configured Linux VPS provides the control needed to build an efficient hosting environment.

Explore Owned Networks KVM VPS Hosting and deploy your next high-performance WordPress website.


Was this answer helpful?

KVM VPS & Dedicated Servers

Deploy a Linux VPS in under 2 minutes — AlmaLinux, Rocky Linux, Ubuntu, Debian. Full root access, KVM virtualization, US and EU locations.

« Back