宝塔面板开启Nginx fastcgi_cache缓存为WordPress提速

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

现在宝塔面板都默认编译了 Nginx ngx_cache_purge 模块,所以我们直接跳过安装方法。

Nginx配置

现在我们开始配置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”;
  • }
  • 需要注意两点

  • 网站的PHP版本建议使用7.4。
  • 缓存清理配置中的 ”服务器外网IP“ 文字需要修改为服务器的IP地址
  • 加好之后的截图如下:

    添加好之后,重载Nginx设置,缓存就加好了,

    WordPress清理缓存插件

    wp后台搜索 Nginx Helper 插件安装启用,这个插件是为 wordpress fastcgi_cache缓存 打造的一个插件,十分的好用。

    判断缓存状态

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

    0

    评论0

    请先
    显示验证码
    没有账号?注册  忘记密码?