前言:
最适合WordPress的静态缓存,免费而高效,本教程将教大家在宝塔面板上开启该缓存为WordPress提速,从此百度也会爱上你的网站哦。
说到wordpress的缓存,大家想到的肯定是 WP-Super-Cache 的静态html缓存,以及 memcached 或 redis 动态缓存,插件的缓存效果肯定是有的,但是容易出现各种问题,比如配置很复杂、配置全英文、插件之间的冲突等,所以今天我要教大家一个更高级的缓存:Nginx fastcgi_cache缓存,直接在nginx层面缓存页面,还支持缓存伪静态!效果比起传统的php缓存好得太多了,因为很多人使用宝塔面板,所以今天的教程是基于宝塔面板的教程。文章源自百科情报站-https://www.bkqbz.com/2382.html
现在宝塔面板都默认编译了 Nginx ngx_cache_purge 模块,所以我们直接跳过安装方法。文章源自百科情报站-https://www.bkqbz.com/2382.html
文章源自百科情报站-https://www.bkqbz.com/2382.html
Nginx配置
全局设置
现在我们开始配置nginx,来到宝塔后台,在软件商店找到Nginx,点击设置按钮,在配置修改中添加以下内容:文章源自百科情报站-https://www.bkqbz.com/2382.html
fastcgi_cache_path /tmp/wpcache levels=1:2 keys_zone=WORDPRESS:250m inactive=1d max_size=1G; fastcgi_temp_path /tmp/wpcache/temp; fastcgi_cache_key "$scheme$request_method$host$request_uri"; fastcgi_cache_use_stale error timeout invalid_header http_500; #忽略一切 nocache 申明,避免不缓存伪静态等 fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
one=WORDPRESS:250m inactive=1d max_size=1G文章源自百科情报站-https://www.bkqbz.com/2382.html
上面的250m是缓存硬盘大小,1d是缓存时间一天,D代表天M代表分, 后面的1G是缓存的内存大小,都可以根据自己的需要来设置。文章源自百科情报站-https://www.bkqbz.com/2382.html
加进去后的截图如下:文章源自百科情报站-https://www.bkqbz.com/2382.html
网站设置
在宝塔后台的网站列表中,找到你的网站,并且点击设置按钮,将以下代码添加到配置文件中去:文章源自百科情报站-https://www.bkqbz.com/2382.html
set $skip_cache 0; #post 访问不缓存 if ($request_method = POST) { set $skip_cache 1; } #动态查询不缓存 if ($query_string != "") { set $skip_cache 1; } #后台等特定页面不缓存(其他需求请自行添加即可) if ($request_uri ~* "/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; } #这里请参考你网站之前的配置,特别是sock的路径,弄错了就502了!如果你的网站使用PHP7.4,就写-74.sock location ~ [^/]\.php(/|$) { try_files $uri =404; fastcgi_pass unix:/tmp/php-cgi-74.sock; fastcgi_index index.php; include fastcgi.conf; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"; #新增的缓存规则 fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache "$upstream_cache_status From $host"; fastcgi_cache WORDPRESS; add_header Cache-Control max-age=0; add_header Nginx-Cache "$upstream_cache_status"; add_header Last-Modified $date_gmt; add_header X-Frame-Options SAMEORIGIN; # 只允许本站用 frame 来嵌套 add_header X-Content-Type-Options nosniff; # 禁止嗅探文件类型 add_header X-XSS-Protection "1; mode=block"; # XSS 保护 etag on; fastcgi_cache_valid 200 301 302 1d; } #缓存清理配置 location ~ /purge(/.*) { allow 127.0.0.1; allow "服务器外网IP"; # 引号要保留 deny all; fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1"; }
添加好之后,重载Nginx设置,缓存就加好了,文章源自百科情报站-https://www.bkqbz.com/2382.html
WordPress清理缓存插件
后台搜索 Nginx Helper 插件安装启用,这个插件是为 wordpress fastcgi_cache缓存 打造的一个插件,十分的好用。(看个人,可用可不用。)文章源自百科情报站-https://www.bkqbz.com/2382.html
纯代码版插件:
利用机制,实现发布文章和评论自动清除缓存。文章源自百科情报站-https://www.bkqbz.com/2382.html
请根据自己的需要把如下代码添加到functions.php 当中即可文章源自百科情报站-https://www.bkqbz.com/2382.html
/** * WordPress Nginx FastCGI缓存清理代码(Nginx-Helper纯代码版) */ //初始化配置 $logSwitch = 0; //配置日志开关,1为开启,0为关闭 $logFile = '/tmp/purge.log'; //配置日志路径 $cache_path = '/tmp/wpcache'; //配置缓存路径 //清理所有缓存(仅管理员) 范例:http://www.bkqbz.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; } } }
现在发布/更新文章、评论提交/审核,就会自动删除当前文章缓存了,发布/更新文章还会清理首页、分类以及相关标签页缓存(不需要可根据代码中的注释进行屏蔽)。文章源自百科情报站-https://www.bkqbz.com/2382.html
另外,如果想清理全部缓存,可在管理员登陆状态下访问首页+?purge=all 参数,文章源自百科情报站-https://www.bkqbz.com/2382.html
比如:http://www.bkqbz.com/?purge=all ,记得要把purge=all添加到网站配置里。其他用户或访客访问这个地址则没有任何作用,如果还不放心也可以自行更改代码中的参数判断字符串。文章源自百科情报站-https://www.bkqbz.com/2382.html
判断缓存状态
按 F12 开启开发者工具,在未登录的情况下访问网站首页,查看文件头,如果出现 HIT 则是缓存了,BYPASS 则是因设置原因未缓存,MISS 即这个页面还没被缓存,新发布或刚被删除的页面,首次访问将出现这个状态,速度杠杠的,如图所示:文章源自百科情报站-https://www.bkqbz.com/2382.html
对于已经设置了不缓存的页面,Nginx fastcgi_cache会直接显示BYPASS,我们如果是登录状态下那是不显示缓存的。文章源自百科情报站-https://www.bkqbz.com/2382.html
如果你发现你的评论过的用户用的是缓存,那应该是WP没有记住cookie,把以下代码加入到functions.php
中即可。文章源自百科情报站-https://www.bkqbz.com/2382.html
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); }
结语
Nginx开启fastcgi_cache缓存对于加快网页响应速度以及节省服务器资源有着非常重要的意义,可以看出来启用缓存后服务器的承载能力有了非常大的提升,本文会不断更新,请关注。文章源自百科情报站-https://www.bkqbz.com/2382.html
文章源自百科情报站-https://www.bkqbz.com/2382.html
1、文章来源于互联网,仅供学习交流使用,严禁用于商业用途,因此造成的法律后果自行承担。
2、本站不对文章内容的完整性和安全性负责,如发现有问题,请及时联系我们进行处理。
3、如果你有比较好的文章需要发布,可以联系站长和小编,或者自行点击 投稿。
4、若文章中有侵权或不适当内容,请告知我们,本站会第一时间进行处理 免责申明。
重庆市 1F
登录回复
经过测试 提速明显
重庆市 2F
登录回复
新增功能欢迎大家测试
重庆市 3F
登录回复
新增 发布文章和评论自动更新缓存