Nginx安装WP Fastest Cache需这样手动添加静态规则

2019年12月19日23:28:15

安装了WP Fastest Cache缓存插件,如果配置不当,可能插件就失效,而在Nginx安装WP Fastest Cache缓存插件后,你还需要这样在conf配置文件里添加几条静态规则,否则,插件无效。

如何添加?

首先打开Nginx配置文件(可以下载文件到本地编辑,也可以直接在linux里用vi或vim编辑器编辑),位置在Nginx安装目录里如:/usr/local/nginx/conf/nginx.conf

然后把下面这段代码添加到Server{}里面:

# WP Fastest Cache缓存在Nginx静态规则 begin
location / {
    if (-f $request_filename) {
        break;
    }
    set $caches 1;
    set $request_file $document_uri;
    set $cache_file ''; 
    if ($request_method = POST) {
        set $caches 0;
    }
    if ($query_string) {
        set $caches 0;
    }
    if ($caches = 0) {
        set $request_file '';
    }
    if ($request_file ~ ^(.+)$) {
        set $cache_file /wp-content/cache/all/$1/index.html;
    }
    if (-f $document_root$cache_file) {
        rewrite ^ $cache_file last;
    }
    if (!-e $request_filename) {
        rewrite . /index.php last;
    }
} 
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# WP Fastest Cache缓存在Nginx静态规则 end

添加后重启Nginx。

上面代码中:

set $cache_file /wp-content/cache/all/$1/index.html;

是设置缓存路径,我们可以更改这个路径。同样,我们可以进入这个目录看看WP Fastest Cache生成的缓存页。

这样设置后,我们在访问网页时就是访问缓存的页面了。

需要注意的是,WP Fastest Cache缓存页面并非在启动时就立即把所有页面都生成缓存页,可能需要过几分钟才生成。我们可以这样来验证访问的网页是否WP Fastest Cache缓存页:

右键点击打开的网页,再点“查看网页源代码”,滚动条拉到最下面,如果看到下面的语句,则表明访问的是缓存页了:

<!-- WP Fastest Cache file was created in xxxxx seconds, on 日期 时间 -->