MSCache Varnish Purge

外掛說明

MSCache Varnish Purge helps WordPress administrators purge the Varnish cache for sites running behind a Varnish HTTP reverse proxy. It is developed by Managed Server S.r.l. and provides settings for configuring the Varnish connection, automatic cache invalidation when content changes, and manual purge tools available from the WordPress admin area.

This plugin is useful when your WordPress site sits behind Varnish and you need cached pages to be invalidated after content is published or updated, or on demand. It requires a reachable Varnish instance whose VCL is configured to accept PURGE requests from the WordPress server (see the FAQ for a reference VCL).

The settings page is available at Settings MSCache Varnish Purge. On WordPress Multisite, shared connection settings are configured at Network Admin Settings MSCache Network, while each site keeps its own purge options.

Key Features

  • Asynchronous raw socket PURGE — sends PURGE requests via a direct TCP socket (fsockopen) without waiting for the Varnish response, so the purge request does not block the WordPress request.
  • Automatic purge on content changes — when a post, page, or custom post type is published, updated, trashed, or deleted, the plugin automatically purges the affected URLs including the post itself, home page, categories, tags, author archives, and date archives.
  • Full cache purge — supports multiple methods for purging the entire cache: PURGE wildcard, PURGE custom path, or BAN with configurable header.
  • Additional URLs — define a list of extra paths to purge alongside content changes or on demand.
  • Exclusion patterns — define glob or regex patterns for URLs that should be excluded from caching. Matching requests receive the ms-cache: excluded HTTP header, which can be used by Varnish to skip caching.
  • Admin bar integration — quick-access purge buttons in the WordPress admin bar: Purge All, Purge Home, Purge Current Page.
  • Bulk and row actions — purge cache for selected posts/pages directly from the list table.
  • Debug logging — optional logging of all purge operations to a protected log directory.
  • PHP 7 and PHP 8 compatible — works on PHP 7.0 through PHP 8.x without deprecation warnings.

How It Works

The plugin opens a raw TCP socket to your Varnish server and sends an HTTP PURGE request with the appropriate Host header. The socket is closed immediately after writing the request — the plugin does not wait for Varnish to respond. This “fire and forget” approach is designed to avoid blocking the WordPress request while the purge is processed.

External Services

This plugin optionally connects to the following external services when configured by the administrator:

Cloudflare API — When the Cloudflare integration is enabled, the plugin sends cache purge requests to the Cloudflare API v4 (https://api.cloudflare.com/client/v4/) to synchronize Varnish cache invalidation with Cloudflare CDN edge cache. This requires a Cloudflare account, a Zone ID, and an API Token with “Zone.Cache Purge” permission. No personal data or visitor information is transmitted — only URL paths and authentication credentials are sent.

Varnish Cache — The plugin opens raw TCP socket connections to a Varnish server at a user-configured IP address and port (default: 127.0.0.1:80). This is typically a localhost connection to infrastructure managed by the site administrator. No external third-party service is contacted for this functionality.

Data Handling & Logging

When debug mode is enabled by the administrator, the plugin logs technical data (URL paths, timestamps, socket connection status, purge results) to files in wp-content/uploads/mscache-logs/. Log files are protected with .htaccess rules, obfuscated filenames, and an index.php guard. No personally identifiable information (PII) or visitor data is collected, stored, or transmitted. Purge statistics (success/failure counts, recent activity) are stored in the WordPress options table and are visible only to administrators.

Configuration

General Settings

  • Enable Plugin — master switch for all purge functionality.
  • Varnish IP — the IP address of your Varnish server (default: 127.0.0.1).
  • Varnish Port — the port Varnish listens on (default: 80).
  • Custom Host Header — override the Host header sent with purge requests. Leave empty to use your WordPress site URL.
  • Socket Timeout — connection timeout in seconds (default: 5).

Automatic Purge

Choose which content changes trigger automatic cache purge:

  • Posts, Pages, Custom Post Types
  • Home page
  • Category, tag, author, and date archives

Full Cache Purge

Three methods are available:

  • PURGE /.* — sends a PURGE request with a wildcard path. Requires Varnish VCL to handle regex/wildcard PURGE.
  • PURGE custom path — sends PURGE to a specific path (e.g., /purge-all). Useful when your VCL maps a special path to a full ban.
  • BAN with custom header — sends a BAN request with a configurable header name and value. The most flexible option but requires matching VCL configuration.

Important: The actual behavior of a full purge depends entirely on your Varnish VCL configuration. The plugin only sends the request — it is your VCL that decides what gets purged.

Additional URLs

Enter one URL per line (absolute or relative paths). These URLs can be purged:

  • Automatically alongside post/page saves (if the option is enabled)
  • Manually via the “Purge Additional URLs” button

Exclusions

Define patterns (one per line) for URLs that should be excluded from caching. Two matching modes:

  • Glob (default) — supports * (any characters) and ? (single character). Example: /wp-admin/*, /cart*, *.xml
  • Regex (advanced) — full regular expression support. Use with caution.

When a frontend request matches an exclusion pattern, the plugin sends the HTTP header ms-cache: excluded. Your Varnish VCL can check for this header and bypass caching accordingly.

Lines starting with # are treated as comments and ignored.

Matching is performed on the request path only, ignoring the query string.

Disclaimer

This plugin is provided “as is” under the terms of the GNU General Public License v2 or later. MANAGED SERVER S.R.L. does not warrant that the plugin will function correctly on hosting environments, servers, or Varnish configurations not directly managed by the company. The plugin has been tested and validated exclusively on the Managed Server hosting infrastructure. Use on third-party environments is at the user’s sole risk and responsibility. In no event shall MANAGED SERVER S.R.L. be liable for any direct, indirect, incidental, or consequential damages arising from the use of this plugin outside of the Managed Server infrastructure.

安裝方式

  1. Upload the mscache-varnish-purge folder to /wp-content/plugins/.
  2. Activate the plugin through the WordPress admin panel.
  3. Go to Settings MSCache Varnish Purge to configure. On a Multisite network, shared connection settings are at Network Admin Settings MSCache Network.
  4. Set the Varnish IP address (default: 127.0.0.1) and port (default: 80).
  5. Enable the plugin and configure automatic purge options.
  6. Make sure your Varnish VCL is configured to handle PURGE requests (see FAQ).

常見問題集

Compatibility and Supported Environments

This plugin has been designed, developed, tested, and validated on the hosting infrastructure of Managed Server S.r.l. — Performance Managed Hosting (managedserver.it). The reference stack consists of Nginx (SSL termination and micro-caching) + Varnish Cache 3.x/4.x (HTTP reverse proxy) + Apache/Nginx (backend) + PHP-FPM, running on Linux.

The plugin communicates with Varnish via raw TCP socket on a configurable IP address and port. Whether it works on other hosting environments depends entirely on:

  • The Varnish version installed and its VCL configuration
  • The IP address and port on which Varnish listens for HTTP requests
  • The network topology (is Varnish on localhost? Behind a load balancer? On a separate machine?)
  • The presence of additional caching layers (Nginx proxy cache, CDN, etc.)
  • ACL rules in the VCL that control which IPs are authorized to send PURGE requests

Other hosting providers that use Varnish Cache may work perfectly with this plugin, provided that their VCL is configured to accept PURGE requests from the WordPress server and that the IP/port are set correctly in the plugin settings.

Disclaimer: MANAGED SERVER S.R.L. does not assume any responsibility, direct or indirect, for malfunctions, data loss, cache inconsistencies, service interruptions, or any other issue arising from the use of this plugin on hosting environments, servers, or infrastructure not directly managed by Managed Server S.r.l. The plugin is provided “as is” under the GPLv2 license. Use on third-party environments is at your own risk and responsibility. We strongly recommend testing thoroughly in a staging environment before deploying to production.

What Varnish VCL do I need?

Your VCL must handle PURGE requests from the WordPress server and optionally support the ms-cache: excluded header for cache exclusions. Below is the reference VCL configuration tested and validated on the Managed Server infrastructure, for Varnish 3.x. Replace 123.123.123.123 with your server’s public IP address and 127.0.0.2 with your actual backend address and port.

vcl_recv — PURGE handling (single URL + full domain):

`
backend website {
.host = “127.0.0.2”;
.port = “80”;
}

sub vcl_recv {

Set X-Forwarded-For header

if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For =
req.http.X-Forwarded-For + “, ” + client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}

—————————————————————

if (beresp.http.ms-cache == “excluded”) {
set beresp.ttl = 0s;
set beresp.http.X-Cache = “EXCLUDED”;

… your other vcl_recv rules …

}

**vcl_fetch — Respect the ms-cache: excluded header from the plugin:**

sub vcl_fetch {

unset beresp.http.ms-cache;

return (hit_for_pass);
}

… your other vcl_fetch rules …

}
`

How does the purge mechanism work?

The plugin sends an HTTP PURGE request to Varnish via a raw TCP socket connection (fsockopen). The request includes the URL path to invalidate and the correct Host header for the domain.

Single URL purge — When a post is saved, the plugin sends:

PURGE /2026/04/03/my-post-title/ HTTP/1.0
Host: www.example.com
Connection: Close

The VCL uses ban() with a regex anchored match (^/path/$) to invalidate the URL. This approach is used instead of return(purge) because most production Varnish configurations include additional keys in vcl_hash (e.g., x-ua-device for mobile/desktop variants). A ban() invalidates all variants of the URL in a single operation, regardless of the hash.

Full cache purge — When “Purge Entire Cache” is clicked, the plugin sends:

PURGE /.* HTTP/1.0
Host: www.example.com
Connection: Close

The VCL interprets /.* as a regex matching all URLs for that host, effectively invalidating the entire domain cache.

Asynchronous (fire-and-forget) — The socket is closed immediately after sending the request. The plugin does NOT wait for Varnish to respond, so the purge request does not block the WordPress request. In debug mode, the plugin reads the response status line for logging purposes.

What is the difference between PURGE and BAN?

  • PURGE (return(purge) in VCL) removes a single cached object matching an exact URL and hash. It is fast and frees memory immediately, but only works for the exact hash — if your vcl_hash includes device type, language, or other keys, you would need a separate PURGE for each variant.

  • BAN (ban() in VCL) adds a rule to the ban list that retroactively invalidates all cached objects matching a condition. Objects are checked against the ban list when they are next requested. BAN is more flexible because it can match patterns (regex) and invalidates all variants of a URL regardless of the hash.

This plugin uses the BAN mechanism (via the PURGE HTTP method) because it is the most reliable approach for production environments with multi-variant caching (mobile/desktop, multilingual, A/B testing, etc.).

What does the ms-cache: excluded header do?

When a frontend request path matches one of the exclusion patterns configured in the plugin settings (e.g., /cart/*, /checkout/*, /my-account/*), the plugin adds the HTTP response header ms-cache: excluded. This header does nothing by itself — it is a signal for your caching layer to skip caching for that response.

In Varnish: The vcl_fetch block shown above checks for this header and sets beresp.ttl = 0s + return(hit_for_pass), ensuring the response is never stored in cache.

In Nginx proxy cache: You can use this header with proxy_no_cache to achieve the same effect. See the Nginx integration section in the plugin documentation.

WooCommerce pages (Cart, Checkout, My Account) can be automatically excluded without manual pattern configuration by enabling the “Auto-Exclude WooCommerce Pages” option in the WooCommerce tab.

Does this plugin work with WordPress Multisite?

Yes. The plugin fully supports WordPress Multisite with a dual-layer configuration:

  • Network-level settings — Varnish IP, port, socket timeout, Cloudflare CDN integration, and third-party plugin integrations are configured once in Network Admin Settings MSCache Network and shared across all sites in the network.
  • Per-site settings — Each site in the network has its own independent configuration for auto-purge options, exclusion patterns, WooCommerce integration, permissions, and debug mode.
  • Dynamic host header — The plugin automatically detects and uses the correct domain name for each site when sending PURGE requests. Sites with custom domains (domain mapping) are supported.
  • Network admin dashboard — Shows all sites in the network with their host headers and plugin status (enabled/disabled) at a glance.
  • WP-CLI — The wp mscache purge-network command purges the cache for all sites in the network in a single operation, iterating through each site with the correct host header.

Is it safe for shared hosting?

Yes. The plugin only opens outbound TCP connections to the configured Varnish IP (default: 127.0.0.1, localhost). It does not require any special PHP extensions beyond the standard fsockopen function available in all PHP installations. It is compatible with PHP 7.0 through PHP 8.x without deprecation warnings.

Why raw sockets instead of wp_remote_request?

The WordPress HTTP API (wp_remote_request) sends the request and waits for the full HTTP response cycle before returning control to WordPress. This adds latency to every post save.

Raw sockets with fsockopen allow the plugin to:

  1. Open a TCP connection to Varnish
  2. Write the PURGE request
  3. Close the connection immediately — without reading the response

This “fire and forget” approach avoids waiting for the full HTTP response cycle on each purge, so the purge request does not block the WordPress admin request regardless of how long Varnish takes to process it.

In debug mode, the plugin optionally reads the first response line (status code) for logging, which adds ~2-3ms but provides valuable diagnostic information.

What integrations are supported?

The plugin integrates with:

  • Cloudflare CDN — Synchronized cache purge via Cloudflare API v4 (per-URL or purge-everything)
  • WP Rocket — Bidirectional sync (MSCache WP Rocket and WP Rocket MSCache)
  • FlyingPress — Bidirectional sync
  • W3 Total Cache — Sync purge (MSCache W3TC)
  • Autoptimize — CSS/JS cache clear on full Varnish purge
  • Redis / Memcached Object Cache — Optional flush on full purge
  • WooCommerce — Dedicated integration with stock, sales, reviews, coupons, attributes, orders, and auto-exclusion of dynamic pages

Each integration is detailed below.

Cloudflare CDN Integration

Many websites use Cloudflare as a CDN and security layer in front of their origin server. When Varnish is purged, the content at the origin is fresh — but Cloudflare edge nodes around the world may still serve stale cached copies to visitors for hours or days.

The plugin solves this by optionally sending purge requests to the Cloudflare API v4 every time Varnish is purged. Configuration requires a Cloudflare API Token (with “Zone.Cache Purge” permission) and the Zone ID of your domain, both available from the Cloudflare dashboard.

Three purge modes are available:

  • Per-URL — Each individual URL purged from Varnish is also purged from Cloudflare. Precise but generates more API calls. Cloudflare free plan allows 1,000 purge API calls per day.
  • Purge Everything — Any Varnish purge event triggers a full Cloudflare cache purge. Simple but clears the entire CDN cache including static assets (CSS, JS, images).
  • Per-URL + full purge fallback (recommended) — Individual page purges are sent per-URL to Cloudflare. Full Varnish purge events trigger a Cloudflare “purge everything”. This mode balances per-URL precision with simplicity.

A Test Connection button in the Cloudflare tab verifies that the API Token and Zone ID are valid and shows the zone name and status.

WP Rocket Integration

WP Rocket is one of the most popular WordPress performance plugins, providing page caching, file optimization, and lazy loading. When both MSCache and WP Rocket are active, two separate caching layers exist: Varnish (server-level) and WP Rocket (application-level). If only one is purged, visitors may see inconsistent content.

The integration provides bidirectional synchronization:

  • MSCache WP Rocket — When MSCache purges a URL from Varnish, it also calls rocket_clean_post() to clear that page from WP Rocket’s local page cache. On a full Varnish purge, rocket_clean_domain() clears the entire WP Rocket cache.
  • WP Rocket MSCache — When a user clicks “Clear Cache” in WP Rocket (or WP Rocket clears cache automatically), MSCache listens to the after_rocket_clean_domain, after_rocket_clean_post, and after_rocket_clean_home hooks and sends corresponding PURGE requests to Varnish.

Important: WP Rocket has its own built-in Varnish add-on. If both the WP Rocket Varnish add-on and this MSCache integration are active simultaneously, you may get duplicate PURGE requests to Varnish. The plugin auto-detects this conflict and displays a warning in the Integrations tab. Disable WP Rocket’s Varnish add-on when using MSCache.

An infinite loop guard prevents MSCache WP Rocket MSCache WP Rocket cycles.

FlyingPress Integration

FlyingPress is a lightweight WordPress performance plugin focused on page caching and CDN. The integration works similarly to WP Rocket:

  • MSCache FlyingPress — Calls FlyingPress\Purge::purge_url() for single pages and FlyingPress\Purge::purge_everything() for full cache purge.
  • FlyingPress MSCache — Listens to the flying_press_purge_everything action. When FlyingPress clears its cache, MSCache also sends a full PURGE to Varnish.

The plugin auto-detects FlyingPress via FLYING_PRESS_VERSION constant or class existence and shows the detection status in the Integrations tab.

W3 Total Cache Integration

W3 Total Cache (W3TC) is a comprehensive performance plugin with page cache, database cache, object cache, and CDN support. The integration is one-directional (MSCache W3TC):

  • When MSCache purges a single URL, it calls w3tc_flush_post() to clear that page from all W3TC cache layers.
  • When MSCache performs a full purge, it calls w3tc_flush_all() to clear the entire W3TC cache.

Important: W3TC has its own Varnish module. If both the W3TC Varnish module and MSCache are active, you will get duplicate PURGE requests. The plugin auto-detects this conflict and warns you. Disable W3TC’s Varnish module when using MSCache.

Autoptimize Integration

Autoptimize aggregates and minifies CSS and JavaScript files to reduce HTTP requests and file sizes. After a theme or plugin update, the optimized asset bundles may reference outdated code.

The integration is one-directional and limited to full purge only:

  • When MSCache performs a full Varnish purge (e.g., after a plugin/theme update), it also calls autoptimizeCache::clearall() to regenerate all optimized CSS/JS bundles.
  • Single page purges do not trigger Autoptimize clear, because regenerating all optimized assets for a single page change would be disproportionately expensive.

This ensures that after major updates, both the Varnish cache and the Autoptimize asset cache are fresh and consistent.

Redis / Memcached Object Cache Integration

WordPress object cache (Redis, Memcached, APCu) stores transients, database query results, and rendered fragments in memory. When Varnish is fully purged (e.g., after a major site update), the object cache may still contain stale data that causes WordPress to render pages with outdated content — even though Varnish fetches fresh HTML from the backend.

The integration is one-directional and limited to full purge only:

  • When MSCache performs a full Varnish purge, it optionally calls wp_cache_flush() to clear the entire object cache.
  • Single page purges do not trigger an object cache flush, because flushing the entire object cache for a single page change would degrade performance.

Use with caution on high-traffic sites: Flushing the object cache causes a temporary spike in database queries as WordPress rebuilds its cached queries and transients. On a high-traffic site this can briefly increase server load.

The plugin auto-detects the active object cache backend (Redis, Memcached, APCu, or none) and displays it in the Integrations tab.

WooCommerce Integration

WooCommerce introduces unique caching challenges: product prices change with sales and coupons, stock quantities change with every order, reviews affect displayed ratings, and pages like Cart, Checkout, and My Account contain user-specific dynamic content that must never be cached.

The plugin provides a dedicated WooCommerce tab with granular control over each integration point:

  • Product stock changes — When a product’s stock is updated (purchase, restock, manual edit), the product page, shop page, and all product category pages are purged. This prevents the common issue where a product shows “In Stock” in the cached page while it is actually sold out.

  • Scheduled sales — WooCommerce uses a cron job to activate and deactivate scheduled sale prices. The plugin hooks into this cron event and purges all products currently on sale plus the shop page, ensuring that sale prices and “On Sale” badges appear and disappear instantly.

  • Product reviews — When a product review is posted, approved, unapproved, or deleted, the product page and shop page are purged to reflect the updated star rating and review count.

  • Coupons — When a coupon is created or modified, the shop page and home page are purged. This is relevant if your shop displays coupon-dependent promotions or pricing.

  • Product attributes — When product attributes (Color, Size, Material, etc.) are renamed, added, or deleted, the shop page is purged to ensure filter/navigation labels are correct.

  • Order status changes — When an order transitions to processing, completed, cancelled, or refunded, the plugin purges the product page, shop page, and product category pages for every product in that order. For example, an order with 6 products triggers purge of all 6 product pages plus their categories and the shop page, in a single deduplicated operation.

  • Auto-exclusion of dynamic pages — Cart, Checkout, and My Account pages are automatically detected using WooCommerce’s own wc_get_page_id() function and marked with the ms-cache: excluded header. This works regardless of custom page slugs or permalink structures, without requiring manual exclusion pattern configuration.

All WooCommerce hooks are registered conditionally — they only activate if WooCommerce is installed and the corresponding option is enabled. If WooCommerce is not active, the entire tab has no effect and no hooks are loaded.

使用者評論

這個外掛目前沒有任何使用者評論。

參與者及開發者

以下人員參與了開源軟體〈MSCache Varnish Purge〉的開發相關工作。

參與者

將〈MSCache Varnish Purge〉外掛本地化為台灣繁體中文版

對開發相關資訊感興趣?

任何人均可瀏覽程式碼、查看 SVN 存放庫,或透過 RSS 訂閱開發記錄

變更記錄

1.0.0

  • Initial release.
  • Asynchronous raw socket PURGE via fsockopen (fire-and-forget).
  • Automatic purge on post, page, and custom post type save, trash, delete, and status transitions.
  • Automatic purge on comment approval, edit, and deletion.
  • Automatic purge on taxonomy term edit and deletion.
  • Automatic purge on nav menu, widget, and Customizer changes.
  • Automatic purge on scheduled post publication (WP-Cron).
  • Automatic purge on plugin, theme, and WordPress core updates.
  • Automatic purge on theme switch and permalink structure change.
  • Automatic purge on featured image change and media attachment updates.
  • Automatic purge on frontend-affecting option changes (site title, blog page, etc.).
  • REST API content update support (Gutenberg editor compatibility).
  • Full cache purge with three configurable methods (wildcard, custom path, BAN).
  • Additional URL list with manual and automatic purge.
  • Exclusion patterns with glob and regex support, pattern tester, and ms-cache: excluded header.
  • WooCommerce integration: stock, scheduled sales, reviews, coupons, attributes, orders, auto-exclusion.
  • AMP page purge support (endpoint /amp/ and query parameter ?amp formats).
  • Cloudflare CDN synchronization (per-URL, purge-everything, hybrid mode).
  • Integrations with WP Rocket, FlyingPress, W3 Total Cache, Autoptimize, and Object Cache.
  • WordPress Multisite support with network-level and per-site settings.
  • WP-CLI commands: purge, purge-network, status, test.
  • REST API endpoints for external purge triggers.
  • Role-based purge permissions.
  • Admin bar with server icon, status indicator, purge buttons, and Purge Page + Archives.
  • Dashboard widget in WP Admin with status, purge count, and quick purge button.
  • Post editor metabox with per-page purge button.
  • Bulk and row actions for purging selected posts/pages.
  • Full cache purge warning modal with confirmation.
  • Frontend toast notification after admin bar purge.
  • Dashboard with purge statistics (7-day history), recent activity log with search, pagination, and user tracking.
  • Connection test with Varnish diagnostic (version detection, response parsing).
  • Import/Export settings as JSON.
  • Debug logging to protected files with daily rotation and admin log viewer.
  • Tabbed settings interface with Dashicons, tooltips, and responsive design.
  • Security: CRLF injection prevention, ReDoS protection, SSRF blocking, log injection sanitization.
  • Translations: English, Italian, French, German, Spanish.
  • PHP 7.0+ and PHP 8.x compatible.
  • GPLv2 or later license.