為了優(yōu)化網(wǎng)站的訪問速度,我們可以通過(guò)對(duì)靜態(tài)內(nèi)容進(jìn)行壓縮,從而減少網(wǎng)頁(yè)加載的時(shí)間,大大節(jié)省用戶的帶寬。在這篇文章中,我將介紹如何使用Apache和.htaccess文件進(jìn)行靜態(tài)內(nèi)容壓縮。
首先讓我介紹一下,我們可以使用兩種不同的方法壓縮內(nèi)容:GZip 和 deflate。
介紹
GZip方法在早期的apache版本中使用(在Apache 1.3之前)。但在那之后apache引入了deflate方法,相比GZip并沒有太大的效果(但仍是非常好的)。然而,GZip在apache 1.3之后不再提供更多的支持。因此,你的Apache版本必須大于1.3,如果沒有,你必須升級(jí)到最新版本的Apache。
在使用壓縮之前,你必須啟用apache的mod_deflate模塊。要啟用這個(gè)模塊,你只需要從httpd.conf文件去掉這個(gè)模塊行。
啟用這個(gè)模塊后,你的服務(wù)器準(zhǔn)備好提供壓縮的內(nèi)容。但是,服務(wù)器只有當(dāng)它接收到來(lái)自客戶端的相應(yīng)頭文件時(shí),才會(huì)創(chuàng)建壓縮內(nèi)容。所以,現(xiàn)在你需要將下面的代碼放置到你網(wǎng)站的htaccess文件,才能通知服務(wù)器提供壓縮的內(nèi)容。
.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>
新聞熱點(diǎn)
疑難解答
圖片精選