Godaddy Linux空间如何开启GZIP

 

近期在主机侦探论坛上,看到一位使用Godaddy的朋友想通过GZIP压缩网页内容。但是Godaddy空间不支持mod_gzipmod_deflate模块。所有只能通过开启zlib.output_compression或者通过ob_gzhandler编码的方式。

zlib.output_compression是和PHP脚本解析程序并行的一个线程,当PHP输入时,这边读入、压缩,而已经压缩好的文档达到一定数量(默认是4K),它就向浏览器发送数据。而ob_gzhandler则是在PHP脚本执行完所有代码才把缓存好的输出文件进行压缩并传输给浏览器,所以相对要慢一点,但是原理是相同的。需要注意的是,两者不同同时使用,否则会出错。

对于Godaddy空间,官方推荐的是使用ob_gzhandler。以下是官方原文:

Compression is a simple, effective way to save bandwidth and speed up your website in Linux Shared Hosting. By adding a piece of PHP code to the top of your Web pages, you can instruct the Web server to compress files for transit to your visitors’ Web browser. This is especially useful for text-heavy Web pages that are over 100K in size.

To Optimize Your Site Using Compression

Add the following code to the very top of your Web pages above the DOCTYPE:

<?php if (substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’], ‘gzip’)) ob_start(“ob_gzhandler”); else ob_start(); ?>


Rename the file you want to compress with a .php extension instead of .html or .htm and upload the file to your site. The file will be compressed upon request and delivered to the visitors’ browser



将以下代码加入到PHP文件的顶部就可以实现GZIP压缩



 

<?php

if(substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’],’gzip’))

ob_star(“ob_gzhandler”);

else

ob_star();

?>



如果不使用官方推荐的ob_gzhandler方式。可以使用zlib.output_compression。默认情况之下,zlib.output_compression是关闭的,如需开启需要编辑php5.ini文件,加入以下内容:



zlib.output_compression=On

zlib.output_compression_level=6



然后将php5.ini文件上传到网站根目录下,等待生效即可。

可以通过phpinfo()函数检查是否生效



Directive Local Value Master Value

zlib.output_compression On On

zlib.output_compression_level 6 6



zlib.output_compressionLocal ValueMasterValue的值同为On时,表示已经生效,这时候访问的PHP页面(包括伪静态页面)已经GZIP压缩了。如果需要使用ob_gzhandler,则需关闭zlib.output_compression,把php5.ini文件内容更改为:



zlib.output_compression = Off

zlib.output_compression_level = -1



不管是zlib.output_compression还是ob_gzhandler,都仅能对PHP文件进行GZIP压缩,对于HTMLCSSJS等静态文件只能通过调用PHP的方式实现。

使用Discuz论坛的朋友要注意一下,Discuz在后台开启GZIP功能的时候,会默认运行ob_gzhandler,所以建议正常情况下将zlib.output_compression设置为off状态。