FastCGI_cache是Nginx的缓存模块,能够从Nginx层面实现网页静态化,有效提高网站的并发能力、减少PHP运行时间和请求响应时间,大大提升页面加载速度。


Fastcgi_cache能够直接在nginx层面提供缓存内容,而无需涉及PHP或WordPress,加速效果比Wp Rocket还好。相比之下缓存插件每个请求仍然需要在应用程序级别由PHP处理,需要消耗更多CPU。


群里有成员说安装对比过觉得Nginx服务器启用fastcgi_cache缓存速度比Litespeed服务器快。不过缓存插件仍然可以附带很多功能,能基准控制缓存的内容等。


当然,前提是你的服务器本身有足够的性能,如果只有1H1G,再怎么优化也无法显著提升效果。现在大部分人建站使用宝塔面板,便捷省事。下面分享宝塔面板开启FastCGI_Cache缓存方法。


注意:由于FastCGI_Cache会缓存PHP请求,可能会导致网站异常。例如阅读量计数失效、缓存评论者信息、缓存登陆界面等,需要添加额外代码修复。新手不建议使用FastCGI_Cache缓存。开启FastCGI_Cache缓存需要使用专门缓存插件,不能使用Wp Rocket之类。


Nginx如何启用fastcgi_cache缓存

宝塔面板默认编译了Nginx ngx_cache_purge 模块,无需额外安装,直接按下面教程操作即可。


全局设置

1登录宝塔后台,在软件商店找到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;


网站设置

在宝塔后台网站列表中找到相应网站,点击“设置”按钮,将以下代码添加到配置文件中。代码要按需调整,第43行输入网站服务器IP(外网)地址。


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";

}



安装WordPress清理缓存插件

FastCGI_Cache无法自动及时精准清理网站缓存,所以需要安装配套缓存插件自动控制刷新缓存。后台搜索、安装Nginx Helper插件,这个插件专门为fastcgi_cache缓存打造,十分的好用。


fastcache


清理模式选择Delete local server cache files,直接从服务器删除缓存文件然后重新生成。


我朋友奶爸建站测试发现Nginx fastcgi_cache缓存(404ms)速度比WP Super Cache + Memcached Object Cache缓存(455ms)快一点.


判断缓存状态

使用浏览器隐身模式打开网站前台(未登录状态),按 F12 进入开发者工具 > “网络” > “点网址” > “选标头”,查看文件头。


HIT 代表命中缓存

MISS 代表没有找到缓存

BYPASS 代表跳过缓存

EXPIRED 代表缓存过期