gzip是一种网络数据压缩传输技巧,可以让我们的带宽省70%左右,这可是一个非常可观的东西了,下面我来给大家整理几种gzip配置方法吧.
第一种方案:在.htaccess 中添加如下代码:
-
AddHandler application/x-httpd-php .css .html .js
-
-
#这是添加你要压缩的类型
-
-
php_value auto_prepend_file “/home/a4284418/public_html/gzip.php”
-
-
#这是你给这些类型增加一个自动运行的php代码,后面一定要填你空间的绝对地址
gzip.php,代码如下:
-
<?php
-
ob_start(“ob_gzhandler”);
-
ob_start(“compress”);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
?>
第二种方案:此种方案是gzip的升级版,可以将gzip的压缩文件缓存下来,避免重复压缩,在.htaccess 中添加:
htaccess RewriteRule (.*.css$|.*.js$) gzip.php?$1 [L],代码如下:
-
<?php
-
-
-
define(‘ABSPATH’, dirname(__FILE__).’/');
-
-
$cache = true;
-
-
$cachedir = ‘gzip-cache/’;
-
if (!is_dir(ABSPATH.$cachedir))
-
{
-
mkdir(ABSPATH.$cachedir);
-
}
-
-
$gzip = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], ‘gzip’);
-
$deflate = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], ‘deflate’);
-
-
$encoding = $gzip ? ‘gzip’ : ($deflate ? ‘deflate’ : ‘none’);
-
if(!isset($_SERVER['QUERY_STRING'])) exit();
-
-
-
$key =basename($_SERVER['QUERY_STRING']);
-
-
$filename=ABSPATH.$_SERVER['QUERY_STRING'];
-
$symbol=’^';
-
$rel_path=str_replace(ABSPATH,”,dirname($filename));
-
$namespace=str_replace(‘/’,$symbol,$rel_path);
-
$cache_filename=ABSPATH.$cachedir.$namespace.$symbol.basename($filename).’.gz’;
-
$type=”Content-type: text/html”;
-
$pathInfo = pathinfo($filename);
-
-
$ext = $pathInfo['extension'];
-
switch ($ext){
-
case ‘css’:
-
$type=”Content-type: text/css”;
-
break;
-
case ‘js’:
-
$type=”Content-type: text/javascript”;
-
break;
-
default:
-
exit();
-
}
-
if($cache)
-
{
-
if(file_exists($cache_filename))
-
{
-
-
$mtime = filemtime($cache_filename);
-
$gmt_mtime = gmdate(‘D, d M Y H:i:s’, $mtime) . ‘ GMT’;
-
-
$content = file_get_contents($cache_filename);
-
header(“Last-Modified:” . $gmt_mtime);
-
header(“Expires: “);
-
header(“Cache-Control: “);
-
header(“Pragma: “);
-
header($type);
-
header(“Tips: Normal Respond (Gzip)”);
-