值此良機,記錄一下解決萬惡的 Google 提供的反動公共庫檔案拖慢整站的問題。如果你的 WordPress 上只跑著一個站點,外掛 Useso take over Google 已經提供了完美的解決方案。但是,如果想要在 WordPress 多站點中,把庫檔案放在每個站點的目錄下呢?

Nginx 反代

公共庫檔案不是隨時更新的內容,所以很適合用快取進一步提速。注意,快取功能需要 nginx cache_purge 模組。

設定快取檔案

編輯 nginx.conf,增加:

proxy_cache_path  /tmp/nginx-cache-googleapis  levels=1:2   keys_zone=cache_googleapis:10m max_size=10g;

指定 ajax 目錄反代

建立 conf.d/proxy-ajax-googleapis.conf,內容如下:

location ^~ /ajax/ {
	proxy_cache_key "$request_uri";
	proxy_cache cache_googleapis;
	proxy_cache_valid  200 304 3h;
	proxy_cache_valid 301 3d;
	proxy_cache_valid any 10s;
	proxy_pass_header Server;
	proxy_set_header User-Agent $http_user_agent;
	proxy_set_header Host googleajax.admincdn.com;
	proxy_redirect off;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Scheme $scheme;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_pass http://googleajax.admincdn.com;
}

對站點啟用

修改 WordPress 站點的 nginx 配置檔案,增加:

include conf.d/proxy-ajax-googleapis.conf;

載入反代配置

在終端中執行:

service nginx reload

訪問一下 https://dallaslu.com/ajax/libs/jquery/1.11.1/jquery.min.js,速度還不錯。

WordPress 引用地址

替換指令碼引用地址

把外掛 Useso take over Google 下載下來,修改 php 檔案中的 function useso_take_over_google_str_handler 為:

function useso_take_over_google_str_handler($matches)
{
	$str = $matches[0];
 
	$str = str_ireplace('//googleajax.admincdn.com', home_url(), $str);
 
	return $str;
}

使外掛生效

將外掛的資料夾名字改為 do-not-use-google-libraries,上傳到 wp-content/plugins,進入管理網路的外掛選單下,選擇在全部站點中啟用。

你猜怎麼著?好使了唄!