宝塔面板开启nginx Fastcgi_cache缓存为wordpress提速

说到wordpress的缓存,大家想到的肯定是 WP-Super-Cache 的静态html缓存,以及 memcached 或 redis 动态缓存,插件的缓存效果肯定是有的,但是容易出现各种问题,比如配置很复杂、配置全英文、插件之间的冲突等,所以今天我要教大家一个更高级的缓存:Nginx fastcgi_cache缓存,直接在nginx层面缓存页面,还支持缓存伪静态!效果比起传统的php缓存好得太多了,因为很多人使用宝塔面板,所以今天的教程是基于宝塔面板的教程。

全局设置

现在我们开始配置nginx,来到宝塔后台,在软件商店找到Nginx,点击设置按钮,在配置修改中添加以下内容:

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;

网站设置

在宝塔后台的网站列表中,找到你的网站,并且点击设置按钮,将以下代码添加到配置文件中去:

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设置,缓存就加好了,

按 F12 开启开发者工具,在未登录的情况下访问网站首页,查看文件头,如果出现 HIT 则是缓存了,BYPASS 则是因设置原因未缓存,MISS 即这个页面还没被缓存,新发布或刚被删除的页面,首次访问将出现这个状态,如图所示:

缓存命中!

相关文章

我想将wordpress的默认接口路由改掉,愿意是默认的带一个 wp...
wordpress自定义分类法之后,我看到链接都自动在后面添加了一...
事情是这样的,我用 get_post_type 函数创建了一个自定义分类...
最近网站莫名其妙的被顶上了,过一个多小时,就注册一个账号...
最近服务器要到期了,就想着把网站转移到另外一台服务器,本...
今天在写wordpress的接口,然后碰到个奇怪的问题,怎么访问都...