让 GZIP 与 cos-html-cache 共存

Posted by David on 2008-03-14 in Blog Related

用过 cos-html-cache 插件的人都知道,cos-html-cache 需要在 Wordpress 后台关闭 gzip 压缩选项才能正常工作。因为 cos-html-cache 只静态化首页和日志页面,这样一来像分类浏览页面、按日期浏览页面、搜索结果页面等等既没有静态化,也没有享受到 gzip 压缩带来的好处。

其实有时候鱼和熊掌还是可以兼得的。Wordpress 后台的 gzip 压缩设置是个全局选项,它不区分页面类型,那么我们可以手动对需要压缩的页面启用 gzip 。将以下代码添加到主题目录下的 functions.php header.php 文件中的 HTML 代码之前:

<?php
// 下面的代码大部分来自 Wordpress 的 gzip_compression 函数
// 如果关闭了 gzip 并且启用了 cos-html-cache 插件
if ( !get_option( 'gzipcompression' ) && function_exists('CosSafeTag')) {
  // 如果不是日志页或者首页
  if(!(is_single() || (is_home() && !is_paged()))){
    if ( ( ini_get( 'zlib.output_compression' ) == 'On' || ini_get( 'zlib.output_compression_level' ) > 0 ) || ini_get( 'output_handler' ) == 'ob_gzhandler' ) {
      // Do nothing
    } else {
      if ( extension_loaded( 'zlib' ) ) {
        ob_start( 'ob_gzhandler' );
      }
    }
  }
}
?>

本来也没想到要这么做,因为折腾 Wordpress 的 404 页面过程中发现打开 gzip 后 IE 就可以正常显示错误页面,索性将其它没有被静态化的页面一并压缩了。

UPDATE at 2008-3-15 21:37
刚才再次测试的时候才发现上面那段代码放在 functions.php 中会工作不正常,因为 WP 加载 functions.php 的时候还没执行查询操作,is_single() 判断根本就不起作用。惭愧,有些粗心大意了。

Tags: , , , .

Comments

  1. 1 tsianreply to this comment

    果然,这里的侧边栏recent comments没有改变。
    任何动态的东西一旦被html化就没法动了。不好玩啊。
    不过貌似cos现在在玩jquery,上帝保佑它用的是ajax载入,就可以避免这个问题了。
    明天问问他去。

  2. 2 tsianreply to this comment

    哇靠,太棒了。当初研究这个问题真是让我头大。

  3. 3 Davidreply to this comment

    Recent Posts, Recent Comments 其实我觉得放在首页就可以了,其它页面没必要放

Leave a Reply

: when reply to my comment.

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!:

You can use these XHTML tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">