代码改变世界

使用nginx-http-concat添加nginx资源请求合并功能

2016-07-14 13:55  hduhans  阅读(3620)  评论(1编辑  收藏  举报

  web项目中有时候一个页面会加载多个js或css资源请求,导致页面加载耗时较长,这时优化的方向可以采用资源合并,可以在客户端事先合并,也可以在服务端进行资源合并,服务端合并的方式使用起来更灵活。

  nginx-http-concat是阿里云开发的nginx开源组件,可以在nginx编译安装时添加模块,也可以在已安装的nginx中重新添加模块。

一、已安装的nginx添加nginx-http-concat模块

  已安装的nginx添加module,需要重新进行编译覆盖,这点与apache不同,apache只需要添加module,然后添加引用即可。

1、添加nginx编译脚本

   1) 查看当前nginx版本,命令:/usr/local/sbin/nginx -v

   2) 下载相应的nginx源码版本,地址:http://nginx.org/download/

   3) 上传到服务器并解压

 2、添加nginx-http-concat源码

   1) 下载module,git地址:https://github.com/alibaba/nginx-http-concat

   2) 上传到服务器并解压,本实验解压地址:/usr/local/nginx/third_module/nginx-http-concat

3、执行重新编译

   1) 查看当前nginx编译参数,执行命令:/usr/local/sbin/nginx -V

   2) 进入nginx源码目录,在获取的编译参数中添加:--add-module=/usr/local/nginx/thrid_module/nginx-http-concat,执行添加后的命令,如:./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_spdy_module --with-http_gzip_static_module --with-ipv6 --with-http_sub_module --add-module=/usr/local/nginx/third_module/nginx-http-concat

   3) 执行编译命令:make,注意编译之后千万不能执行make install

   4) 编译完后,当前nginx源码目录下生成objs目录则说明编译成功

4、覆盖nginx执行脚本

   1) 备份当前nginx执行脚本,命令:cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak。如果拷贝出错,则将nginx进行杀掉再进行,命令:killall nginx

   2) 拷贝上一步骤编译后的新nginx脚本,命令:cp /mnw/download/nginx-1.8.0/objs/nginx /usr/local/nginx/sbin/

   3) 查看编译参数,命令:/usr/local/nginx/sbin/nginx -V,如果编译参数中存在刚添加的模块,则说明编译成功

   4) 重启nginx

二、配置使用nginx-http-concat模块

1、配置项

   1) concat,是否打开资源合并开关,选项:on | off,默认:off

   2) concat_types,模块处理的资源类型,默认:text/css application/x-javascript

   3) concat_unique,是否允许合并不同类型的资源,选项:on | off,默认:on

   4) concat_max_files,允许合并的最大资源数目,默认:10

   5) concat_delimiter,合并后的文件内容分隔符,用于区分不同文件的内容

   6) concat_ignore_file_error,是否忽略404或403错误,选项:on | off,默认:off

2、配置实例

   1) nginx添加配置

location /static/css/ {
    concat on;
    concat_delimiter /* my file */; 
}

   2) 重启nginx,命令:/usr/local/nginx/sbin/nginx -s reload

   3) 创建测试文件,在web目录下创建/static/css目录,并创建文件a.css、b.css,内容随意。

   4) 请求地址:http://localhost/my-web/static/css??a.css,b.css,如看到返回a.css、b.css合并内容,则整个配置完成。注意,url中static/css目录必须真实存在,且a.css与b.css必须位于此目录中