Table of contents of the article:
What is MSCache Varnish Purge?
MSCache Varnish Purge is a professional WordPress plugin that allows you to asynchronously invalidate (purge) the Varnish cache via raw TCP sockets, without impacting site performance. Designed and optimized for the Managed Server Srl hosting stack, it is compatible with any properly configured Varnish Cache installation.
Unlike many plugins on the market, which make synchronous HTTP requests to Varnish (or even to intermediate endpoints), MSCache Varnish Purge completely avoids blocking the WordPress execution process. Traditional plugins wait for a response from the Varnish server before continuing, introducing additional latency with every save, publish, or update of content. This behavior, especially on high-traffic sites or with many concurrent operations, can result in noticeable slowdowns on the backend and an overall degradation in performance.
The plugin instead sends HTTP requests PURGE directly to Varnish via fsockopen, immediately closing the connection without waiting for the server's response — a “fire and forget” approach that completely eliminates waiting times. This way it is guaranteed zero additional latency on every WordPress operation, while maintaining a fast, efficient, and scalable invalidation mechanism.
This asynchronous approach makes MSCache Varnish Purge particularly effective even in complex scenarios, where purges are frequent and must be performed without compromising the responsiveness of the administration interface or application operations.
Why do I need a purge plugin for Varnish?
Varnish cache It's an HTTP accelerator that sits in front of the backend and stores copies of already generated web pages, serving them directly to visitors without having to involve WordPress, PHP, and MySQL each time. This significantly reduces response times, lightens the load on the application server, and improves the site's ability to handle a large number of concurrent requests.
The problem arises when the content changes: a post is updated, a comment is approved, or a WooCommerce product goes out of stock. Without an invalidation mechanism, Varnish continues to serve the old (stale) version of the page until the natural TTL expires, risking showing visitors outdated content.
MSCache Varnish Purge solves this problem by automatically notifying Varnish whenever WordPress content changes, surgically purging only the affected URLs—the modified post, the home page, category and tag archive pages, and any other associated URLs. This allows you to maintain the benefits of caching without sacrificing consistency and the immediate updating of published content.
Main features
Automatic purge on content changes
The plugin monitors all relevant WordPress events and automatically sends purge requests to Varnish:
- Articles and Pages — purge on saving, updating, publishing, trashing and deleting
- Home page — automatically purged upon each content change (configurable)
- Category and Tag Archives — archive pages are purged when an article belonging to that category/tag is modified
- Author Archives — the author page is updated when the author publishes or modifies an article
- Data Archives — the year, month, and day archives are purged when an article with that date is modified
- Custom Post Type — full support for any type of custom content
- RSS feed — the feed is purged to ensure that RSS readers receive new content immediately
- Editorials — when a comment is approved, edited, or deleted, the post page is purged to reflect the updated count
- Taxonomic terms — when a category or tag is renamed or deleted, the corresponding archive is purged
- Menu navigazione — menu changes trigger a purge of the home page or the entire cache
- Widgets and Customizers — changes to WordPress widgets and customizer settings
- Scheduled Posts — posts scheduled for future publication are automatically purged when WordPress cron publishes them
- Featured image — changing the featured image of a post triggers a purge even without saving the post
- Core, plugin, and theme updates — a full purge is performed automatically after every update
- Change theme — changing the active theme triggers a full purge
- Change permalink — changing the permalink structure triggers a full purge
- Frontend options changes — changes to the site title, description, home page, or blog page trigger a complete purge
- Gutenberg Editor — full support via REST API hooks as a fallback for block editor saves
Manual purge
In addition to automatic purging, the plugin offers several ways to perform manual purges:
- Admin bar — “MSCache” menu in the administration bar with:
- Purge entire cache (with confirmation popup and performance warning)
- Purge home page
- Purge current page (available on the frontend)
- Purge page + archives (full purge like autosave)
- Actions Tab — dedicated buttons on the plugin configuration page
- Metabox in the editor — “Purge This Page” button in the editor sidebar to purge the page you are editing
- Row action — “Purge Cache” link in the post/page list to purge individual contents
- Bulk action — mass action to purge the cache of multiple selected posts at once
Configurable full purge
Purge of the entire cache supports three methods, configurable based on the Varnish VCL in use:
- PURGE wildcard (
PURGE /.*) — sends a request with path regex that matches all URLs in the domain - PURGE personalized path — send a PURGE to a specific URL that the VCL maps to a full ban
- BAN with custom header — sends an HTTP BAN method with a custom header (e.g.
X-Purge-Regex: .*)
Cache exclusions
The plugin allows you to define patterns for URLs that should never be cached. When a frontend request matches an exclusion pattern, the plugin adds the HTTP header ms-cache: excluded to the answer.
This header is read from the Varnish VCL (or from the configuration proxy_no_cache (Nginx) to prevent caching of that response.
Matching mode
- Glob (default) — use simple wildcards:
*matches any sequence of characters,?to a single character. Examples:/wp-admin/*,/cart*,/checkout*,*.xml - regex (advanced) — full PCRE regular expressions with built-in ReDoS protection (backtracking limit reduced to 10.000)
Pattern tester
A built-in tool in the Exclusions tab lets you test whether a URL matches a configured pattern, without having to make any real requests.
WooCommerce Self-Exclusion
The Cart, Checkout, and My Account pages are automatically excluded from the cache when this option is enabled, without the need to manually configure patterns.
WooCommerce Integration
MSCache Varnish Purge includes a dedicated tab for WooCommerce with granular integration across every aspect of e-commerce:
- Change of stock — when the stock quantity of a product changes (purchase, restocking, manual change), the product page, shop page and category pages are purged
- Scheduled sales — the WooCommerce cron that activates and deactivates the sales automatically triggers the purge of the sale products and the shop page
- Product Reviews — when a review is published, approved, or deleted, the product page is purged to reflect the updated rating
- Coupon — Creating or editing coupons triggers a purge of the store and home pages
- Product attributes — changes to attributes (Color, Size, Material) trigger a purge of the store page
- Change order status — when an order changes status (processing, completed, cancelled, refunded), the plugin purges the product page, shop page and categories each product contained in the order
- Self-exclusion — Cart, Checkout and My Account are automatically excluded from the cache via the header
ms-cache: excluded
CloudFlare CDN Integration
For sites using Cloudflare as their CDN, the plugin offers automatic cache synchronization: whenever Varnish is purged, the Cloudflare edge cache is also invalidated.
Configuration
- Token API — with “Zone.Cache Purge” permission (not Global API Key)
- ID area — domain zone identifier on Cloudflare
- Connection test — button to verify that the credentials are valid
Purge mode
- Per-URL — every URL purged from Varnish is also purged individually on Cloudflare (note, multiple API calls)
- Purge Everything — any Varnish purge triggers a “purge everything” on Cloudflare (simple, it flushes the entire CDN)
- Per-URL + fallback (recommended) — purge per-URL for individual pages, “purge everything” only when doing a full Varnish purge
Integrations with performance plugins
The plugin integrates bidirectionally with major WordPress performance plugins, keeping all caching layers synchronized.
WP Rocket
WP Rocket It's one of the most popular and high-performance caching plugins for WordPress, designed to improve page loading speed and user experience without requiring complex configuration. Through features such as page caching, CSS and JavaScript optimization, lazy loading, and cache preloading, it dramatically reduces frontend response times.
- MSCache → WP Rocket — when Varnish is purged, WP Rocket's local page cache is cleaned via
rocket_clean_post()erocket_clean_domain() - WP Rocket → MSCache — when the user clicks “Clear Cache” in WP Rocket, Varnish is also purged
- WP Rocket's Varnish add-on auto-detect with warnings to avoid double purges
FlyingPress
FlyingPress It's a WordPress performance optimization plugin focused on real-world user-perceived speed, with a modern and highly efficient approach. It includes features such as page caching, JavaScript execution optimization and delay, advanced lazy loading, critical CSS, and intelligent resource preloading, helping to significantly improve metrics such as Core Web Vitals and overall loading times.
- Two-way synchronization via
FlyingPress\Purge::purge_url()and action hookflying_press_purge_everything - Plugin auto-detect with status indicator
W3 Total Cache
W3 Total Cache It's one of the most popular WordPress performance optimization plugins, designed to offer advanced control over all levels of caching. It supports page cache, object cache, database cache, and CDN integration, as well as CSS and JavaScript minification tools. Its flexibility makes it suitable for complex configurations, although it requires proper setup for best results.
- One-way synchronization (MSCache → W3TC) via
w3tc_flush_post()ew3tc_flush_all() - W3TC native Varnish module auto-detect with conflict warning
Autoptimize
Autoptimize It's a lightweight WordPress plugin dedicated to optimizing frontend assets, aiming to reduce the size and number of HTTP requests. It primarily aggregates, minifies, and compresses CSS and JavaScript files, as well as optimizing the loading of resources and, optionally, images. It's often used in conjunction with caching systems to further improve overall site performance.
- Optimized CSS/JS cache cleaning only on Varnish full purge, via
autoptimizeCache::clearall() - It does not trigger on purge single pages to avoid excessive asset regenerations
Object Cache (Redis / Memcached)
Redis Object Cache Redis is a plugin that allows you to use Redis as an object caching system for WordPress, storing frequently requested data such as database queries and PHP objects in memory. This reduces the number of MySQL accesses and significantly improves backend performance, especially on high-traffic or complex sites. It's particularly effective when integrated into an optimized server-side stack.
- Optional WordPress object cache flush (
wp_cache_flush()) on complete purge of Varnish - Backend auto-detect (Redis, Memcached, APCu)
Every integration has a anti-loop guard which prevents endless cycles of mutual purges.
AMP Pages
The plugin supports automatic purging of AMP versions of pages, in both formats:
- Endpoint —
/post-slug/amp/(used by the official AMP plugin and AMP for WP) - Query parameter —
/post-slug/?ampe/post-slug/?amp=1
When enabled, corresponding AMP variants are also generated and purged for each purged URL. The plugin automatically detects the AMP format in use.
WordPress Multisite
MSCache Varnish Purge fully supports WordPress Multisite with a two-tier configuration:
- Network settings — IP Varnish, port, timeout, Cloudflare and third-party integrations are shared between all sites and managed by the Network Admin
- Per-site settings — automatic purge options, exclusions, WooCommerce and permissions are configurable independently on each site
- Dynamic Host Header — the plugin automatically uses the correct domain for each site in the network, also supporting domain mapping
- Network Dashboard — shows all sites with their host header and plugin status
- WP-CLI — command
wp mscache purge-networkto purge all sites in one operation
Role-based permissions
Access to purge functions is configurable per WordPress role:
- CEO — always enabled, full access to settings
- Editor, Author, other roles — Individually configurable. Enabled roles see the purge buttons in the admin bar and post lists, but they don't have access to the plugin's configuration page.
WP-CLI
The plugin offers full WP-CLI commands for automation and deployment scripts:
# Purge dell'intera cache
wp mscache purge --all
# Purge di una URL specifica
wp mscache purge --url=/shop/
# Purge della home page
wp mscache purge --home
# Purge delle URL aggiuntive configurate
wp mscache purge --additional
# Stato configurazione
wp mscache status
# Test connessione a Varnish
wp mscache test
# Purge di tutti i siti nel network (Multisite)
wp mscache purge-network
REST API
Authenticated endpoints for purge triggers from external systems, CI/CD pipelines, or custom integrations:
# Purge di una URL specifica
curl -X POST https://example.com/wp-json/mscache/v1/purge \
-H "Authorization: Basic ..." \
-d '{"url": "/shop/"}'
# Purge completo
curl -X POST https://example.com/wp-json/mscache/v1/purge \
-d '{"all": true}'
# Stato del plugin
curl https://example.com/wp-json/mscache/v1/status
Authentication uses the standard WordPress system (Application Passwords, cookie auth, or any authentication plugin).
Dashboard and monitoring
Plugin Dashboard
The Dashboard tab on the setup page shows:
- Status — plugin enabled/disabled, Varnish connection OK/FAIL, target IP:port, host header, Multisite status
- Purge Statistics — success/failure count per day over the last 7 days
- Last failure — timestamp and path of the last failed purge
- Recent activity — Last 500 purge operations with timestamp, path, result, trigger, and username. 50-record pagination per page with URL search.
WP Dashboard Widgets
A compact widget in your WordPress main dashboard that shows at a glance:
- Connection status (green/red/grey dot)
- Target Varnish
- Purge counter of the day
- Last purge with timestamp and path
- Quick button “Purge Entire Cache”
Debug log
When debug mode is enabled, the plugin logs every purge operation to daily log files:
- Purged URL path
- Varnish Response (HTTP Code)
- Socket connection errors
- Matched Exclusion Patterns
- Timestamp in UTC format
Logs are protected with .htaccess, obfuscated filenames with random tokens, and a index.php guard. A log viewer integrated into the settings page displays the last 50 lines of the current day's log.
Safety
- CRLF injection — all values injected into raw HTTP requests are sanitized against
\r\n\0 - SSRF — block link-local and cloud metadata IPs (169.254.xx) in Varnish IP configuration
- ReDoS — reduced backtracking limit to 10.000 for regex patterns, path truncation to 2.048 characters
- Log injection — sanitization of newlines in log messages
- Log file exposure — random token in file names, protection
.htaccesseindex.php - CSRF — nonce verification on all admin actions
- Capability check —
manage_optionsfor settings,current_user_can_purge()for purge actions - Input sanitization —
sanitize_text_field(),sanitize_textarea_field(),intval(),FILTER_VALIDATE_IP, whitelist for select fields - Output escaping —
esc_html(),esc_attr(),esc_url(),wp_kses()on all admin outputs - Hostname validation — regex
/^[a-zA-Z0-9._-]+$/for the custom host header - Zone ID validation — 32-character hex regex for Cloudflare Zone ID
VCL Varnish Configuration
The plugin is tested and proven on the Varnish stack from Managed Server Srl. Below is the reference VCL configuration for Varnish 3.x or later.
vcl_recv — PURGE Management
backend website {
.host = "127.0.0.2";
.port = "80";
}
sub vcl_recv {
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 (req.request == "PURGE") {
if ((req.http.X-Forwarded-For == "123.123.123.123, 127.0.0.1")
|| (req.http.X-Forwarded-For == "127.0.0.1")) {
ban("req.url ~ ^" + req.url + "$"
+ " && req.http.host == " + req.http.host);
error 200 "Purged.";
} else {
error 405 "Not allowed.";
}
}
if ((req.request == "PURGE")
&& ((req.http.X-Forwarded-For == "123.123.123.123")
|| (req.http.X-Forwarded-For == "127.0.0.1"))
&& (req.http.X-Purge-Domain)) {
ban("req.http.host == " + req.http.X-Purge-Domain);
error 200 req.http.X-Purge-Domain + " purged.";
}
# ... altre regole vcl_recv ...
}
vcl_fetch — ms-cache exclusions
sub vcl_fetch {
if (beresp.http.ms-cache == "excluded") {
set beresp.ttl = 0s;
set beresp.http.X-Cache = "EXCLUDED";
return (hit_for_pass);
}
# ... altre regole vcl_fetch ...
}
Replace 123.123.123.123 with the server's public IP and 127.0.0.2 with the backend address.
Compatibility
| Components | Supported versions |
|---|---|
| Wordpress | 5.0+ |
| PHP | 7.0 — 8.x |
| Varnish cache | 3.x, 4.x, 5.x, 6.x, 7.x |
| WooCommerce | 3.x — 9.x |
| multisite | Yes |
Available languages
- English (default)
- Italian
- French
- German
- Spanish
Other languages will probably be integrated in the future (Chinese, Japanese, Romanian, Russian, Greek, Finnish)
Installation
- Load the directory
mscache-4-wpin/wp-content/plugins/ - Activate the plugin from the WordPress Plugins panel
- Going up MSCache in the side menu
- Configure Varnish IP and port (default: 127.0.0.1:80)
- Enable the plugin from the General tab
- Use the button Test Connection in the Actions tab to check connectivity
Requirements
- PHP 7.0 or higher with function
fsockopenenabled - Varnish Cache installed and reachable via TCP from the configured IP
- VCL configured to accept PURGE requests (see VCL Configuration section)
Disclaimer
This plugin is distributed under the GPLv2 license or later. It is designed and optimized for the Managed Server Srl hosting infrastructure. It can function properly on any hosting environment with a properly configured Varnish Cache. MANAGED SERVER SRL assumes no responsibility for malfunctions, data loss, cache inconsistencies, or service interruptions resulting from the use of the plugin on environments not managed by the company. It is recommended to test thoroughly in a staging environment before deploying to production.