最近群裡的小夥伴又在抱怨安裝的 WordPress cms 主題載入太慢了,其實呢 cms 主題嘛,首頁的文章展示模組太多了,所以產生的 sql 查詢也就多了,自然而然的載入速度也就很慢咯尤其是資料展示量比較的 cms 主題,那載入速度可不敢恭維了。那麼如何加快解構比較複雜的 WordPress cms 主題的載入速度呢?小編這裡給出兩個方案。

方案一:在伺服器上安裝 eaccelerator 或 memcached 這類的資料庫快取指令碼,並且安裝相關的 WordPress 外掛。 (PS:這個方案適合 vps 或者獨立伺服器的使用者,如果小夥伴用的是虛擬主機那就別奢望這個方法了。)

方案二:為 WordPress 首頁生成一個 html 檔案跳過 sql 查詢。 (這個方法最有效,效果也很好,而且對小夥伴的空間配置要求不高,虛擬主機即可使用。)

實現方法:

1 、新建一個名為 index_html.php 的檔案並加入一下程式碼:

<?php
$baseCmsUrl = "http://www.weixiaoduo.com";   //你網站的根目錄不要加反斜槓/
$dmPageName = "index.php";
$stPageName = "index.html";
$tureStFile = dirname(__FILE__).'/'.$stPageName;
{
        $body = file_get_contents($baseCmsUrl.'/'.$dmPageName);
        $fp = fopen($tureStFile, 'w');
        fwrite($fp, $body);
        fclose($fp);
}
header("Location:$baseCmsUrl/index.html");    //生成後返回靜態首頁
?>

將檔案上傳到網站根目錄後直接開啟瀏覽器訪問該檔案即可為 WordPress 首頁生成 html 。

生成 index.html 檔案後,我們要注意的是我們直接訪問自己的域名和訪問域名+index.html 都會顯示首頁這樣的會搜尋引擎會認為你在製造重複頁面,會給網站帶來一定的負面影響,下面小編給出解決此問題的方法 (訪問 index.html301 轉跳到/,即去除掉首頁 url 中的 index.html):

apache 下的解決方法:

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /index.(php|html|htm) HTTP/
RewriteRule ^index.(php|html|htm)$ https://www.weixiaoduo.com/ [R=301,L]

nginx 下的解決方法

location / {
     if (!-e $request_filename){
          rewrite ^/(.*)$ /index.html/$1 last;
     }
}

apache 下只要將程式碼加到.htaccess 檔案最上面即可,域名替換成你自己的域名,至於 nginx,小編就不多說了,既然你都用上了 nginx 那麼這點問題應該還是懂的。

2014 年 1 月 15 日更新

解決 index_html.php 檔案只能執行一次的問題。 (PS:群裡有位小夥伴使用了小編的靜態化首頁的方法加速首頁,但是發現 index_html.php 檔案只能生成一次 index.html 檔案,第二次執行後 index.html 檔案無變化,只有登入 FTP 刪除了之後再次生成才有用。) 使用改良後的程式碼即可解決此問題,程式碼如下:

<?php
if(file_exists("index.html"))
 {
unlink("index.html");
 }
$baseCmsUrl = "http://www.weixiaoduo.com";
$dmPageName = "index.php";
$stPageName = "index.html";
$tureStFile = dirname(__FILE__).'/'.$stPageName;
{
        $body = file_get_contents($baseCmsUrl.'/'.$dmPageName);
        $fp = fopen($tureStFile, 'w');
        fwrite($fp, $body);
        fclose($fp);
}
header("Location:$baseCmsUrl/index.html");
?>