为了优化网站的访问速度,咱们能够经过对静态内容进行压缩,从而减小网页加载的时间,大大节省用户的带宽。在这篇文章中,我将介绍如何使用Apache和.htaccess文件进行静态内容压缩。javascript
首先让我介绍一下,咱们可使用两种不一样的方法压缩内容:GZip 和 deflate。css
介绍html
GZip方法在早期的apache版本中使用(在Apache 1.3以前)。但在那以后apache引入了deflate方法,相比GZip并无太大的效果(但还是很是好的)。然而,GZip在apache 1.3以后再也不提供更多的支持。所以,你的Apache版本必须大于1.3,若是没有,你必须升级到最新版本的Apache。java
在使用压缩以前,你必须启用apache的mod_deflate模块。要启用这个模块,你只须要从httpd.conf文件去掉这个模块行。apache
启用这个模块后,你的服务器准备好提供压缩的内容。可是,服务器只有当它接收到来自客户端的相应头文件时,才会建立压缩内容。因此,如今你须要将下面的代码放置到你网站的htaccess文件,才能通知服务器提供压缩的内容。json
.HTACCESS代码服务器
<ifmodule mod_deflate.c=""> # force deflate for mangled headers # developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/ <ifmodule mod_setenvif.c=""> <ifmodule mod_headers.c=""> SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding </ifmodule> </ifmodule> # HTML, TXT, CSS, JavaScript, JSON, XML, HTC: <ifmodule filter_module=""> FilterDeclare COMPRESS FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css FilterProvider COMPRESS DEFLATE resp=Content-Type $text/plain FilterProvider COMPRESS DEFLATE resp=Content-Type $text/xml FilterProvider COMPRESS DEFLATE resp=Content-Type $text/x-component FilterProvider COMPRESS DEFLATE resp=Content-Type $application/javascript FilterProvider COMPRESS DEFLATE resp=Content-Type $application/json FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xhtml+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/rss+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/atom+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/vnd.ms-fontobject FilterProvider COMPRESS DEFLATE resp=Content-Type $image/svg+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/x-font-ttf FilterProvider COMPRESS DEFLATE resp=Content-Type $font/opentype FilterChain COMPRESS FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no </ifmodule> <ifmodule !mod_filter.c=""> # Legacy versions of Apache AddOutputFilterByType DEFLATE text/html text/plain text/css application/json AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE text/xml application/xml text/x-component AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml AddOutputFilterByType DEFLATE application/atom+xml AddOutputFilterByType DEFLATE image/svg+xml application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font-ttf font/opentype </ifmodule> </ifmodule>
将上面的代码放置在你的htaccess文件以后,看看你网站的请求头部。你能够看到一个额外的头“Accept-Encoding“。这意味着请求的客户端可以处理给定的压缩类型的内容,并将提供压缩内容。app
Accept-Encoding:gzip,deflate,sdch
结果ide
看看下面的图片,有多少被压缩了。svg
从上面的图片能够看出,实际页面大小707KB,使用压缩后是401KB。所以,它最终会提升你的网站的性能。
结论
我强烈建议你把网站静态内容作压缩处理,由于没有理由不这么作,这是Web开发的一个最佳实践。