apache+tomcat 增加deflate压缩模块

来源:互联网 发布:中兴算法工程师面试题 编辑:程序博客网 时间:2024/06/06 09:06
2010-01-22 10:17

apache2之后版本,内建一个mod_deflate模块,可以对内容压缩后再传送给客户端
这样的好处是节省网络带宽,对低带宽的客户端会加快页面显示响应
好像默认这个模块是不开启的,需要简单配置一下:

  • 打开 httpd.conf 配置文件
  • 确认下面两个模块是打开的:
    LoadModule deflate_module modules/mod_deflate.so
    LoadModule headers_module modules/mod_headers.so
  • 增加如下配置:
  • <VirtualHost localhost>
    <Location "/">
           SetOutputFilter DEFLATE
    AddOutputFilterByType DEFLATE text/html text/plain text/xml
  • AddOutputFilter DEFLATE css     
  • AddOutputFilter DEFLATE js         
  • #AddOutputFilter 添加要压缩的类型这里压缩了: 文本 css js
  •         BrowserMatch ^Mozilla/4 gzip-only-text/html
            BrowserMatch ^Mozilla/4/.0[678] no-gzip
            BrowserMatch /bMSIE !no-gzip !gzip-only-text/html
            SetEnvIfNoCase Request_URI /.(?:gif|jpe?g|png)$ no-gzip dont-vary
             Header append Vary User-Agent env=!dont-vary
         </Location>  
  • </VirtualHost>
  • 其实tomcat本身在5.0版本以后是支持内容压缩的,它使用的是gzip的压缩格式,我们先来看 Tomcat文档中对下面两个配置的注解(红色粗体字部分)

    compressableMimeType

    The value is a comma separated list of MIME types for which HTTP compression may be used. The default value is text/html,text/xml,text/plain.

    compression

    The Connector may use HTTP/1.1 GZIP compression in an attempt to save server bandwidth. The acceptable values for the parameter is "off" (disable compression), "on" (allow compression, which causes text data to be compressed), "force" (forces compression in all cases), or a numerical integer value (which is equivalent to "on", but specifies the minimum amount of data before the output is compressed). If the content-length is not known and compression is set to "on" or more aggressive, the output will also be compressed. If not specified, this attribute is set to "off".

    这两个配置是在servere.xml中的Connector部分,第一个配置是指定Tomcat压缩哪些内容,第二个配置是指示Tomcat是否启用压缩,默认是关闭的。所以假设我们要让Tomcat在默认的8080端口上的输出内容进行压缩,我们的配置应该是:

        <Connector port="8080" protocol="HTTP/1.1"
                   maxThreads="150" connectionTimeout="20000"
                   redirectPort="8443" compression="on"/>

然后就可以了,怎么看效果呢,用firebug看响应,会看到
Content-Encoding : gzip
的response header

推荐:http://www.port80software.com/products/httpzip/在线查看响应速度,压缩率

注:apache功能很强大 这里简单配置一下 ,还有更加详细配置  

原创粉丝点击