Skip to content

Instantly share code, notes, and snippets.

@richardsweeney
Last active March 30, 2022 16:17
Show Gist options
  • Save richardsweeney/736465dddce8398357a9 to your computer and use it in GitHub Desktop.
Save richardsweeney/736465dddce8398357a9 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: NGINX FastCGI cache purge
* Version: 0.1
* Description: Flush NGINX FastCGI cache purge
* Author: The Shipyard Crew
* Author URI: https://theshipyard.se/
* Plugin URI: https://theshipyard.se/
* Text Domain: nginx-fastcgi-cache-purge
* @package NGINX FastCGI cache purge
*/
if ( ! defined( 'NGINX_CACHE_PATH' ) ) {
define( 'NGINX_CACHE_PATH', '/var/run/nginx-cache' );
}
final class NGINX_FastCGI_cache_purge {
public static $instance = null;
private function __construct() {
add_action( 'edit_post', [ $this, 'purge_cache' ] );
}
/**
* Creates or returns an instance of this class.
*
* @return A single instance of this class.
*/
public static function init() {
if ( self::$instance === null ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Purge a page from the NGINX FastCGI cache.
*
* @param int $post_id WP_Post ID.
*/
public function purge_cache( $post_id ) {
if ( 'publish' !== get_post_status( $post_id ) ) {
return;
}
$public_post_types = get_post_types([ 'public' => true ]);
$post_type = get_post_type( $post_id );
if ( ! in_array( $post_type, $public_post_types ) ) {
return;
}
$url = get_permalink( $post_id );
if ( ! $url ) {
return;
}
$path = $this->get_cache_path( $url );
if ( $path ) {
$this->flush_cache( $path );
}
}
/**
* Get the path to the cached file from the URL.
*
* @param string $url URL to parse.
*
* @return string path to the cached page.
*/
protected function get_cache_path( $url ) {
if ( ! $url ) {
return false;
}
$url = parse_url( $url );
$hash = md5( $url['scheme'] . 'GET' . $url['host'] . $url['path'] );
$path = trailingslashit( NGINX_CACHE_PATH );
return $path . substr( $hash, -1 ) . '/' . substr( $hash, -3, 2 ) . '/' . $hash;
}
/**
* Flush the cache from the path to the cached file.
*
* @param string $path Path to the cached file to flush.
*
* @return bool True on success or false.
*/
protected function flush_cache( $path ) {
if ( file_exists( $path ) ) {
return unlink( $path );
}
return false;
}
}
NGINX_FastCGI_cache_purge::init();
@chenr2
Copy link

chenr2 commented Jan 19, 2018

Hi Richard,

Great blog post. We ran into a similar issue with flushing the cache, so we wrote a plugin Cache Sniper for Nginx, which lets you purge the entire cache or single pages, and can be configured to automatically purge on update or comment. Just need to point to the cache folder to match your configuration, i.e. wp option add nginx_cache_sniper_path '/var/run/nginx-cache' --allow-root.

Robert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment