最近羣裏的小夥伴又在抱怨安裝的 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"); ?>