欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Apache / .htaccess 开启 Gzip 和 http缓存

shiping1 的头像

Apache / .htaccess 开启 Gzip 和 http缓存

基本搞网赚的都用的美国的空间,很多空间默认是没有开启 gzip 压缩的。开启压缩可以大大减少下载的网页的大小,也就是减少了下载的时间。

网上一直流传,如果visitor不能在5秒内打开你的网站,那么他就会选择关掉页面。开启gzip压缩后,visitor 会觉得网站载入速度快了,有助于留住流量。

我们可以在 .htaccess 添加下面命令来开启 Gzip

<ifmodule mod_deflate.c>
AddOutputFilter DEFLATE html xml php js css
</ifmodule>

修改后马上就能生效。用火狐的 HTTP Header 插件,可以观察到:

Capture_247.jpg

————–
同时再开启缓存功能,就是告诉客户端的浏览器,缓存文件多长时间。在这段时间内,只要客户不清空浏览器缓存,客户再次打开一个页面时,页面上的图片、css、js、swf就不会再从服务器上下载,而是从客户硬盘上的浏览器缓存文件夹里读取,这样又可以减少客户打开网页的时间。

<ifmodule mod_expires.c>
  ExpiresActive On
  ExpiresDefault A3600
  ExpiresByType text/css A3600
  ExpiresByType text/html A3600
  ExpiresByType application/x-javascript A3600
  ExpiresByType image/gif "access plus 2 month"
  ExpiresByType image/jpeg "access plus 2 month"
  ExpiresByType image/png "access plus 2 month"
  ExpiresByType image/x-icon "access plus 2 month"
  ExpiresByType application/x-shockwave-flash A2592000
 
  Header unset Pragma
  FileETag None
  Header unset ETag
  <filesmatch ".(css|ico|jpg|jpeg|png|gif|js|pdf|flv|mp3|mp4|swf)$">
    Header append Cache-Control "public"
  </filesmatch>
</ifmodule>

A3600 里的 3600 意思是 3600 秒(即1个小时)。具体时间根据自己网站更新情况来改。
修改 .htaccess 后马上生效。

================================

要是自己的独立服务器,不想每个站都改 .htaccess 文件,可以在 http.conf 文件里启动全局性的 gzip。首先找到下面2行,把前面的 # 去掉

LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so

然后找个位置,或者在 httpd.conf 末尾加上(其实把这段放到 .htaccess 也不错,内容更全面) :

<ifmodule mod_deflate.c>
    SetOutputFilter DEFLATE
 
    SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI .(?:pdf|mov|avi|mp3|mp4|rm)$ no-gzip dont-vary
 
    AddOutputFilterByType DEFLATE text/*
    AddOutputFilterByType DEFLATE application/ms* application/vnd* application/postscript application/javascript application/x-javascript
    AddOutputFilterByType DEFLATE application/x-httpd-php application/x-httpd-fastphp
 
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4.0[678] no-gzip
    BrowserMatch bMSIE !no-gzip !gzip-only-text/html
 
    Header append Vary User-Agent env=!dont-vary
</ifmodule>

——————-

全局性启用 缓存:

先去掉 LoadModule expires_module modules/mod_expires.so 前面的 #,然后把上面那一段 <IfModule mod_expires.c> 加到 http.conf 末尾就行

Incoming search terms:

来自 http://www.yed.info/archives/774.html
普通分类: