Hugo博客公告弹窗

提升网站速度:配置 Nginx FastCGI 缓存

   
文章摘要
本文介绍了如何在 Ubuntu 22.04 系统上使用宝塔面板配置 Nginx FastCGI 缓存,以提升网站速度。详细步骤包括:检查 ngx_cache_purge 模块、创建缓存文件夹、配置 Nginx 缓存路径和参数、设置缓存键和使用条件、以及配置网站缓存规则。同时,还提供了 WordPress 环境下的缓存配置方法和注意事项,如修改 php 配置、使用 Nginx Helper 插件或纯代码方式实现缓存清理。

本文介绍如何在 Ubuntu 22.04 系统上使用宝塔面板配置 Nginx FastCGI 缓存,以提升网站速度。

环境:

  • 系统: Ubuntu 22.04
  • 面板: 宝塔面板 7.7.0
  • Nginx 版本: 1.25.5

步骤

1. 检查缓存模块

确认 ngx_cache_purge 模块已安装:

nginx -V 2>&1 | grep -o ngx_cache_purge

2. 创建缓存文件夹

注意:最好是在/var/cache/目录下创建,否则重启服务器会导致nginx无法启动

mkdir -p /var/cache/nginx/catpdf_org
chmod -R 755 /var/cache/nginx/catpdf_org

3. 配置 Nginx 缓存

在 Nginx 配置文件的 server 块前添加:

fastcgi_cache_path /var/cache/nginx/catpdf_org levels=1:2 keys_zone=CATPDF.ORG:200m inactive=2d max_size=10G;
fastcgi_cache_key "$scheme$request_method$host$request_uri$is_args$args";
fastcgi_cache_use_stale error timeout invalid_header http_500 http_503;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

4. 配置站点缓存

在站点配置文件的 #SSL-END 后添加:

# 配置 Nginx fastcgi_cache START
set $skip_cache 0;

# 定义不缓存的条件
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
if ($request_uri ~* "purge=all|/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { set $skip_cache 1; }
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1; }

location ~ [^/]\.php(/|$) {
    try_files $uri =404;
    fastcgi_pass unix:/tmp/php-cgi-74.sock;
    fastcgi_index index.php;
    include fastcgi.conf;  

    # 缓存规则
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    fastcgi_cache CATPDF.ORG;
    fastcgi_cache_valid 200 301 302 1d;

    # 安全头部
    add_header Strict-Transport-Security "max-age=15552000; includeSubdomains; preload";
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Cache "$upstream_cache_status From $host";
    add_header Cache-Control "max-age=86400";
    add_header Nginx-Cache "$upstream_cache_status";
    add_header Last-Modified $date_gmt;

    etag on;
}

# 缓存清理配置
location ~ /purge(/.*) {
    allow 127.0.0.1;
    allow "8.8.8.8";
    deny all;
    fastcgi_cache_purge CATPDF.ORG "$scheme$request_method$host$1";
}
# 配置 Nginx fastcgi_cache END

WordPress 配置 Nginx fastcgi_cache 注意事项

  1. add_header Cache-Control如果是动态内容要实时更新的话,可以设置为0,否则可以设置时间大一些,默认单 位是秒; 2.sock的路径一定要填对,否则会出现502错误;例如:fastcgi_pass unix:/tmp/php-cgi-74.sock; 表示php为7.4版本

3.代码里面的服务器公网IP换成你的服务器公网IP,须保留双引号; 4.可选缓存配置:某些主题如果移动端访问报错,可以设置不缓存移动端,参考写法:

    #不缓存移动端访问
    if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry|windowss(ce|phone))) {
            set $skip_cache 1;
    }

如果评论过的用户加载的是缓存,那应该是WordPress没有记住Cookie,尝试把以下代码加入到functions.php 中:

//nginx-cache 缓存配置代码
add_action('set_comment_cookies','coffin_set_cookies',10,3);
function coffin_set_cookies( $comment, $user, $cookies_consent){
   $cookies_consent = true;
   wp_set_comment_cookies($comment, $user, $cookies_consent);
}

启用fastcgi_cache缓存时,发现在Nginx配置文件中添加了Cache-Control信息,但是总是不生效。HTTP头部信息会总会包含以下信息:

Cache-Control: no-store,no-cache,must-revalidate,post-check=0,pre-check=0 和 Pragma: no-cache

打开php配置,查找

session.cache_limiter = nocache

改成

session.cache_limiter = none

WordPress缓存处理

Nginx Helper插件

进入WordPress 后台插件安装界面搜索 Nginx Helper 关键词在线安装即可

1)开启purge,选择nginx Fastcgin cahe,因为就我们用就是这个缓存。

2)选择 Delete local server cache files。当然第一个也可以用,但是一般推荐用Delete local server cache files,因为每个服务器的环境都不一样,缓存路径也会不尽相同就会导致插件无法找到缓存文件并删除!

插件法注意事项

由于插件作者定义的缓存路径是/var/run/nginx-cache, 解决办法是在插件中找到这一处路径,并替 换成我们自己上边设置的路径/tmp/nginx-cache/catpdf_org

定义缓存路径的位置在/wp-content/plugins/nginx-helper/includes/class-nginx-helper.php,约88行位置。

如果怕更新插件忘了改,那么最好是在WordPress根目录下的wp-config.php中新增如下代码即可(不知道添 加到第几行的话,可以添加到 define(‘WPLANG’,‘zh_CN’);的后面。添加后建议重载一下PHP,确保变量 生效(主要针对开启了PHP缓存的网站),

 //根据实际情况定义缓存的存放路径
define('RT_WP_NGINX_HELPER_CACHE_PATH','/tmp/nginx-cache/catpdf_org');

纯代码版

为张戈大佬原创:https://zhang.ge/5112.html,搬运如下

将整段粘贴到 WordPress 主题函数模板文件 functions.php 当中即可。其他功能细项,在代码和原文中都有详细的注释了,自行参考修改

/**
* WordPress Nginx FastCGI 缓存清理代码(Nginx-Helper 纯代码版) By 张戈博客
* 文章地址:https://zhang.ge/5112.html
* 转载请保留原文出处,谢谢合作!
*/
//初始化配置
$logSwitch  = 0;                  //配置日志开关,1 为开启,0 为关闭
$logFile    = '/tmp/purge.log';   //配置日志路径
$cache_path = '/tmp/nginx-cache/catpdf_org';     //配置缓存路径
//清理所有缓存(仅管理员) 范例: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;
        }
    }
}

多站点设置

如果要开启更多站点缓存,按照上面的教程在对应网站添加即可,注意事项如下:

  • **每个站点的缓存路径 (fastcgi_cache_path)和缓存密钥( keys_zone )设置为不一样的 **
  • 同一个顶级域名下面的子域名不需要加上面配置中的第一行,注释掉
fastcgi_cache_key "$scheme$request_method$host$request_uri";
CC BY-NC-SA 4.0 转载请注明
最后更新于 2024-09-17 13:18
clarity统计