转“nginx 预压缩(gzip)静态文件”

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$content_type"';

    access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    gzip_static on;

    gzip  on;
    gzip_min_length 10;
    gzip_buffers    4 8k;
    gzip_comp_level 9;
    gzip_types      text/plain application/x-javascript text/css application/xml;
    upstream newshooserver {
        server 192.168.106.81:80;
    }
    server {
        listen       8091;
        server_name  192.168.106.81;
        index index.jsp;
        location / {
            proxy_pass http://newshooserver;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        location ~ .*\.(jsp|action){
            gzip off;
            proxy_pass http://newshooserver;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }





转http://willko.iteye.com/blog/667091

对于静态文件先压缩再输出是再正常不过的事了,但是这种压缩都是动态的,在每次请求都会先压缩再输出,大大浪费了很多cpu。如果前端加了反向代理缓存,那能减少这种浪费。但不是每个生产环境前端都有缓存的。而nginx有个模块Gzip Precompression,这个模块的作用是对于需要压缩的文件,直接读取已经压缩好的文件(文件名为加.gz),而不是动态压缩,对于不支持gzip的请求则读取原文件。 

编译nginx的时候需要把--with-http_gzip_static_module参数加上。 

配置: 
Java代码  
#启动预压缩功能,对所有类型的文件都有效  
gzip_static on;  
  
#找不到预压缩文件,进行动态压缩  
gzip on;   
gzip_min_length 1000;  
gzip_buffers 4 16k;  
gzip_comp_level 5;  
gzip_types text/plain application/x-javascript text/css application/xml;  
  
#gzip公共配置  
gzip_http_version 1.1  
gzip_proxied expired no-cache no-store private auth;  
  
#纠结的配置  
#对于ie有个bug,响应vary头后将不会缓存请求,每次都会重新发新的请求。所以,对于ie 1-6直接禁用gzip。  
gzip_disable "MSIE [1-6]\.";  
#开启Http Vary头,vary头主要提供给代理服务器使用,根据Vary头做不同的处理。例如,对于支持gzip的请求反向代理缓存服务器将返回gzip内容,不支持gzip的客户端返回原始内容。  
gzip_vary on;  

gzip_static配置优先级高于gzip
开启nginx_static后,对于任何文件都会先查找是否有对应的gz文件
gzip_types设置对gzip_static无效
为了方便生产环境自动生成压缩文件,写了一条命令自动完成这些事情 
根据文件后缀名遍历需要压缩的文件
对比文件的修改时间
自动调用gzip生成压缩文件
Java代码  
find ./ -type f -printf '%TY %Tm %Td %TH %TM %TS\t%p\n'  
| grep -iE '\.(html|txt|css|js)$'  
| awk -F'\t' '{  
  
gz_file=$2 ".gz";  
stat_cmd="stat -c \"%Y\" " gz_file;  
exist_cmd="[  -e \"" gz_file "\" ] && echo 1 || echo 0";  
  
exist_cmd | getline gz_file_exist;  
  
if (gz_file_exist) {  
    stat_cmd | getline last_modify_timestamp;  
} else {  
    last_modify_timestamp=0;  
}  
  
if (last_modify_timestamp < mktime($1)) {  
    system("gzip -c9 " $2 " > " gz_file);  
    print gz_file " [created]";  
}  
  
}'  


chrome将不会支持gzip了,而用SDCH,SDCH比较像浏览器级的minify 

猜你喜欢

转载自haoningabc.iteye.com/blog/1168441