
0x01.About
源代码已经上传到github:https://github.com/grasses/nginx-lua-static-merger
nginx-lua-static-merger
是一个基于openresty的模块,主要用于合并静态文件。降低http请求,加快静态文件訪问速度的模块。
使用nginx-lua-static-merger
须要在编译nginx时候加入openresty的模块,或者直接安装openresty作为server。
nginx-lua-static-merger
能够让你的js、css请求不要那么多。一个就够了。

0x02.About Nginx
nginx工作
先从nginx原理来看nginx处理http请求的过程。
Nginx的模块从功能上分为例如以下三类:
Handlers(处理器模块),直接处理请求,并进行输出内容和改动headers信息等操作。Handlers处理器模块一般只能有一个。
Filters (过滤器模块),主要对其它处理器模块输出的内容进行改动操作,最后由Nginx输出。
Proxies (代理类模块),Nginx的HTTP Upstream之类的模块。这些模块主要与后端一些服务比方FastCGI等进行交互。实现服务代理和负载均衡等功能。

也就是说。一个http请求过来,nginx先处理请求信息,然后过滤信息,最后丢给代理来处理,它本身处理的东西并不多。它不过通过查找配置文件将此次请求映射到一个location block,而此location中所配置的各个指令则会启动不同的模块去完毕工作。
从正常来看,一个页面载入10来个js、css是正常的,还有10来个图片,即使是什么也不干。那么一个页面也要处理掉20多个http请求,每一个http请求都要跑一遍TCP请求,nginx回应。过滤,分配。
speed test:
看张图吧,国外一个网速測试工具:

去掉首页index.html
的载入时间。能够看到,载入静态文件css,js时间耗费了非常长的等待时间。而且image的载入是在js和css载入完后才载入的。也就是说,假设js或css载入慢了,那么页面就慢了。
这个页面是github.com/grasses。
0x02.Usage
Openresty
Openresty是国人写的开源项目,打包了标准的 Nginx 核心。非常多的经常使用的第三方模块,以及它们的大多数依赖项。
tar xzvf ngx_openresty-VERSION.tar.gz
cd ngx_openresty-VERSION/
./configure
make
make install
具体的安装教程还是去看官网吧。
file path
|--/usr/local/openresty/nginx
| `--lua
| `--nginx-lua-static-merger.lua
| `--conf
| `--nginx.lua
|--/www/openresty/static
| `--js
| `--css
| `--cache
注意
1、nginx.conf
中的lua_package_path "/usr/local/openresty/lualib/?.lua;;";
和
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
,假设你是编译nginx而不是直接安装openresty,文件夹记得放对。
2、确保/www/openresty/static
有Lua写的权限。
use
前端调用方法例如以下:
<link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css;/qiniu/css/main.css;/css/navbar.css">
<script src="/js/jquery.min.js;/js/main.js;/qiniu/bootstrap/js/bootstrap.min.js;/qiniu/js/plupload/plupload.full.min.js;/qiniu/js/plupload/i18n/zh_CN.js"></script>
0x03.How it work
Nginx在location通过 content_by_lua_file
把接下来的处理丢个Lua做逻辑。
Lua通过uri进行md5编码,推断cache是否存在,假设cache不存在。循环切割、遍历uri,訪问响应的路径。查找静态文件,存在则记录,最后写cache入文件。方便下次訪问。

0x04.Effect
以下是在不作处理情况请求多个js结果:

以下是第一次请求下,lua既要获取数据又要合并生成cache,属于冷数据:


第二次訪问就是热数据了,訪问速度是添加的:

本文出自 夏日小草,转载请注明出处:http://homeway.me/2015/06/22/nginx-lua-static-merger/
-by小草
2015-06-22 20:04:10