說到wordpress的緩存,大家想到的肯定是?WP-Super-Cache?的靜態(tài)html緩存,以及?memcached?或?redis?動態(tài)緩存,插件的緩存效果肯定是有的,但是容易出現(xiàn)各種問題,比如配置很復(fù)雜、配置全英文、插件之間的沖突等,所以今天我要教大家一個更高級的緩存:Nginx fastcgi_cache緩存,直接在nginx層面緩存頁面,還支持緩存?zhèn)戊o態(tài)!效果比起傳統(tǒng)的php緩存好得太多了,因為很多人使用寶塔面板,所以今天的教程是基于寶塔面板的教程。

現(xiàn)在寶塔面板都默認(rèn)編譯了?Nginx ngx_cache_purge?模塊,所以我們直接跳過安裝方法。
Nginx配置
現(xiàn)在我們開始配置nginx,來到寶塔后臺,在軟件商店找到Nginx,點擊設(shè)置按鈕,在配置修改中添加以下內(nèi)容:
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 申明,避免不緩存?zhèn)戊o態(tài)等
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
加好之后截圖如下:
網(wǎng)站設(shè)置
在寶塔后臺的網(wǎng)站列表中,找到你的網(wǎng)站,并且點擊設(shè)置按鈕,將以下代碼添加到配置文件中去:
set $skip_cache 0;
#post 訪問不緩存
if ($request_method = POST) {
set $skip_cache 1;
}
#動態(tài)查詢不緩存
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;
}
#這里請參考你網(wǎng)站之前的配置,特別是sock的路徑,弄錯了就502了!如果你的網(wǎng)站使用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";
#新增的緩存規(guī)則
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 "服務(wù)器外網(wǎng)IP"; # 引號要保留
deny all;
fastcgi_cache_purge WORDPRESS "$scheme$request_method$host$1";
}
需要注意兩點
- 網(wǎng)站的PHP版本建議使用7.4。
- 緩存清理配置中的 ”服務(wù)器外網(wǎng)IP“ 文字需要修改為服務(wù)器的IP地址
加好之后的截圖如下:
添加好之后,重載Nginx設(shè)置,緩存就加好了,
WordPress清理緩存插件
wp后臺搜索?Nginx Helper?插件安裝啟用,這個插件是為?wordpress fastcgi_cache緩存?打造的一個插件,十分的好用。
判斷緩存狀態(tài)
按?F12?開啟開發(fā)者工具,在未登錄的情況下訪問網(wǎng)站首頁,查看文件頭,如果出現(xiàn)?HIT?則是緩存了,BYPASS?則是因設(shè)置原因未緩存,MISS?即這個頁面還沒被緩存,新發(fā)布或剛被刪除的頁面,首次訪問將出現(xiàn)這個狀態(tài),如圖所示: