WordPress使用 Nginx Helper 插件清理 fastcgi_cache 缓存

什么是 Nginx Helper?

Nginx Helper是一款免费的开源插件,专为在 Nginx 服务器上运行的 WordPress 网站而设计。它是 WordPress 和 Nginx 之间的重要桥梁,让您更轻松地管理缓存、简化配置并提升网站整体性能。

主要优点
  • 简化配置——无需复杂的手动设置。
  • 改进的性能– 确保您的 WordPress 网站在 Nginx 上顺利运行。
  • 细粒度的缓存管理——直接从 WordPress 仪表板清除和管理缓存文件。
  • 轻巧、干净——完全免费、无广告、易于使用。
安装

您可以直接在 WordPress 官方插件库中找到该插件。只需搜索“Nginx Helper”,然后从 WordPress 管理面板安装并激活即可。

如何为 WordPress 配置 Nginx Helper 插件

Nginx Helper插件允许运行在 Nginx 上的 WordPress 网站高效地管理 FastCGI 缓存。以下是如何设置该插件以及如何选择合适的缓存清除方法。

1.启用缓存清除和预加载
  • 转到插件设置并检查选项以启用缓存清除和缓存预加载。
2.选择Nginx FastCGI缓存
  • 选择“Nginx FastCGI Cache”作为缓存方法。
3.选择缓存清除模式
  • 同一服务器上的多个网站:选择“使用 GET 请求 PURGE/url”
  • 服务器上的单个网站:选择“删除本地服务器缓存文件”

使用GET请求 PURGE/url

  • 该插件向 Nginx 发送类似的请求。PURGE /your/url
  • Nginx 将使用配置来定位并删除相应的缓存文件。fastcgi_cache_key
  • 要求和注意事项:
    • 保持 Nginx 设置中配置的清除路径。
    • 为了安全起见,清除访问通常仅限于特定的 IP。
    • 如果您使用 CDN,请将您的域名添加到指向服务器真实 IP 的位置。这样可以确保插件可以直接清除缓存,而无需经过 CDN,避免请求被阻塞。/etc/hosts
  • 如果这个设置看起来太复杂,那么跳过这个模式会更安全。

删除本地服务器缓存文件

  • 该插件直接从服务器文件系统中定义的目录中删除缓存文件。RT_WP_NGINX_HELPER_CACHE_PATH
  • 不需要 ngx_cache_purge 模块。

要求:

  1. 缓存目录结构必须遵循levels=1:2
  2. 缓存键必须是:"$scheme$request_method$host$request_uri"
  3. 缓存必须驻留在本地服务器上(不能是远程或共享存储)。

重要的:

  • 该插件的默认缓存路径是。/var/run/nginx-cache
  • 如果您的服务器使用自定义缓存路径,插件可能无法定位和删除文件。
  • 要解决此问题,请编辑插件文件:/wp-content/plugins/nginx-helper/includes/class-nginx-helper.php第 88 行左右,用实际的缓存目录替换默认路径。

此设置可确保您的 WordPress 网站可以有效地清除和管理 Nginx FastCGI 缓存,无论是使用直接文件删除还是 PURGE 请求。

Nginx Helper

这部分默认即可:

Nginx Helper

如果你有自定义存档页等非标准页面,需要清除缓存可以把URL单独列在下面,只填你域名后面的部分:

Nginx Helper

免插件清理 fastcgi_cache(Nginx Helper 纯代码版)

Nginx Helper 这款插件主要用于 Nginx fastcgi_cache 缓存或 Redis 缓存清理,用起来确实不错,但因为某些原因你实在不想用插件的话,也可以使用张戈的纯代码。

/**
* WordPress Nginx FastCGI 缓存清理代码(Nginx-Helper 纯代码版) By 张戈博客
* 文章地址:https://zhang.ge/5112.html
* 转载请保留原文出处,谢谢合作!
*/
 
//初始化配置
$logSwitch  = 0;                  //配置日志开关,1 为开启,0 为关闭
$logFile    = '/tmp/purge.log';   //配置日志路径
$cache_path = '/tmp/wpcache';     //配置缓存路径,设置为你的缓存路径
 
//清理所有缓存(仅管理员) 范例:http://www.domain.com/?purge=all
if ($_GET['purge'] == 'all' && is_user_logged_in()) {
    if( current_user_can( 'manage_options' )) 
    {
        delDirAndFile($cache_path, 0);
    }
}
 
//缓存清理选项
add_action('publish_post', 'Clean_By_Publish', 99);                   //文章发布、更新清理缓存
add_action('comment_post', 'Clean_By_Comments',99);                   //评论提交清理缓存(不需要可注释)
add_action('comment_unapproved_to_approved', 'Clean_By_Approved',99); //评论审核清理缓存(不需要可注释)
 
//文章发布清理缓存函数
function Clean_By_Publish($post_ID){
    $url = get_permalink($post_ID);
 
    cleanFastCGIcache($url);        //清理当前文章缓存
    cleanFastCGIcache(home_url().'/');  //清理首页缓存(不需要可注释此行)
        
    //清理文章所在分类缓存(不需要可注释以下 5 行)
    if ( $categories = wp_get_post_categories( $post_ID ) ) {
        foreach ( $categories as $category_id ) {
            cleanFastCGIcache(get_category_link( $category_id ));
        }
    }
 
    //清理文章相关标签页面缓存(不需要可注释以下 5 行)
    if ( $tags = get_the_tags( $post_ID ) ) {
        foreach ( $tags as $tag ) {
	    cleanFastCGIcache( get_tag_link( $tag->term_id ));
        }
    }
}
 
// 评论发布清理文章缓存
function Clean_By_Comments($comment_id){
    $comment  = get_comment($comment_id);
    $url      = get_permalink($comment->comment_post_ID);
    cleanFastCGIcache($url);
}
 
// 评论审核通过清理文章缓存
function Clean_By_Approved($comment)
{
    $url      = get_permalink($comment->comment_post_ID); 
    cleanFastCGIcache($url);
}
 
//日志记录
function purgeLog($msg)
{
    global $logFile, $logSwitch;
    if ($logSwitch == 0 ) return;
    date_default_timezone_set('Asia/Shanghai');
    file_put_contents($logFile, date('[Y-m-d H:i:s]: ') . $msg . PHP_EOL, FILE_APPEND);
    return $msg;
}
 
// 缓存文件删除函数
function cleanFastCGIcache($url) {
    $url_data  = parse_url($url);
    global $cache_path;
    if(!$url_data) {
        return purgeLog($url.' is a bad url!' );
    }
 
    $hash        = md5($url_data['scheme'].'GET'.$url_data['host'].$url_data['path']);
    $cache_path  = (substr($cache_path, -1) == '/') ? $cache_path : $cache_path.'/';
    $cached_file = $cache_path . substr($hash, -1) . '/' . substr($hash,-3,2) . '/' . $hash;
    
    if (!file_exists($cached_file)) {
        return purgeLog($url . " is currently not cached (checked for file: $cached_file)" );
    } else if (unlink($cached_file)) {
        return purgeLog( $url." *** CLeanUP *** (cache file: $cached_file)");
    } else {
        return purgeLog("- - An error occurred deleting the cache file. Check the server logs for a PHP warning." );
    }
}
 
/**
 * 删除目录及目录下所有文件或删除指定文件
 * 代码出自 ThinkPHP:http://www.thinkphp.cn/code/1470.html
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录,1 或 true 删除目录,0 或 false 则只删除文件保留目录(包含子目录)
 * @return bool 返回删除状态
 */
function delDirAndFile($path, $delDir = FALSE) {
    $handle = opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}

将整段粘贴到 WordPress 主题函数模板文件 functions.php 当中即可。现在发布/更新文章、评论提交/审核,就会自动删除当前文章缓存了,发布/更新文章还会清理首页、分类以及相关标签页缓存(不需要可根据代码中的注释进行屏蔽)。

另外,如果想清理全部缓存,可在管理员登陆状态下访问首页+?purge=all 参数,比如:https://soez.website/?purge=all ,其他用户或访客访问这个地址则没有任何作用,如果还不放心也可以自行更改代码中的参数判断字符串。经过测试,这种带参数的路径同样会被 Nginx 缓存,也就说?purge=all 只能用一次,第二次刷新就没效果了,因为被 Nginx 缓存了,要解决也很简单,在网站的 fastcgi 缓存配置中排除这个路径即可:

# 后台/特殊页面不缓存
if ($request_uri ~* "purge=all|/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
    set $skip_cache 1;
}

这些配置能基本满足大部分网站的缓存需求。

相关文章
Elementor Explained
Disable WordPress Image Cropping
use-postfix-smtp-on-your-vps
Make WordPress Faster
Configuration-for-Nginx-FastCGI-Cache
Undefined Array Key ‘path’
vps-from-scratch
website hosting tips
网站托管
The Evolving World of Domains

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

最新文章
滚动到顶部