5. nginx静态资源处理

基本配置

#开启sendfile
sendfile on; 
#sendfile开启的状况下,针对多个tcp请求,进行延时打包处理,能够有效提升网络包的传输效率
tcp_nopush on;
#keepalive链接下,对tcp请求当即响应,与tcp_nopush刚好相反,能够提升网络包的传输实时性
tcp_nodelay off;
#对响应的内容,进行压缩
gzip on;
#设置压缩等级,范围1~9,数值越大,文件越小。压缩等级过高的话,对服务器和浏览器的性能都有很大影响
gzip_comp_level 1;
#代表gzip http协议的版本
gzip_http_version 1.1;
#设置压缩类型,默认状况下只会压缩text/html
gzip_types text/html image/png image/jpeg

资源压缩相关模块

模块 说明
ngx_http_gzip_module 提供基础的gzip支持
ngx_http_gzip_static_module 在向客户端返回常规文件以前,先查找是否存在该常规文件的.gz文件,有的话就直接返回.gz文件
ngx_http_gunzip_module 若是响应内容是gzip的,而浏览器不支持的话,能够经过此模块在返回给浏览器以前进行解压

ngx_http_gzip_module 是默认编译到nginx的发行版本里面的,用户访问的同时,对文件进行压缩,耗CPU。
ngx_http_gzip_static_module 须要编译进去才能有。提早压缩,而后用户访问的时候,返回已经压缩好的,耗磁盘空间。html

# always 就是无论浏览器支不支持都返回.gz内容,此时最好开启ngx_http_gunzip_module模块
gzip_static always;

是否使用gzip,以及使用不一样的gzip方式,http的响应头以下:node

  • 未使用 gzip
Accept-Ranges:bytes
Content-Length:75882
  • 使用 gzip on; 的方式
Content-Encoding:gzip
Transfer-Encoding:chunked
  • 使用 gzip_static on; 的方式
Content-Encoding:gzip
Content-Length:65052