为什么 gzip 压缩对 PHP 处理的文件不起作用?

Why does gzip compression not work for files processed by PHP?

我的服务器上有两个名为 test.htmltest.php 的文件,它们的内容相同:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>TEMPLATE</title>
</head>
<body>

  TEXT

</body>
</html>

除此之外,我还有一个 .htaccess 文件,内容如下:

RewriteEngine On
RewriteBase /
RewriteRule ^(.*)\.(php3|php4|php5|php6|html|htm) \.php

AddType x-mapp-php5.5 .php
AddHandler x-mapp-php5.5 .php

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html
</Ifmodule>

请求 test.html returns 以下 header:

Connection: Keep-Alive
Content-Type: text/html
Date: Fri, 01 Jul 2016 08:32:04 GMT
Keep-Alive: timeout=2, max=200
Server: Apache
Transfer-Encoding: chunked
x-powered-by: PHP/5.5.36

在取消注释重写部分后(因此使用 HTML 而不被 PHP 处理),响应 header 是:

Accept-Ranges: bytes
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 186
Content-Type: text/html
Date: Fri, 01 Jul 2016 08:42:22 GMT
Etag: "xxxxxxxx-xx-xxxxxxxxxxxxx"
Keep-Alive: timeout=2, max=200
Last-Modified: Fri, 01 Jul 2016 08:42:03 GMT
Server: Apache
Vary: Accept-Encoding

一模一样的内容,一模一样header,但是为什么PHP返回的时候内容没有压缩?

在您的 .htaccess

中添加以下行
php_value zlib.output_compression 1

启用PHP 输出压缩。

更多信息请见http://php.net/manual/en/zlib.configuration.php#ini.zlib.output-compression