nginx配置合并js和css文件请求

问题

我在查看jd网站首页代码时候发现好几个这样的url请求:
http://misc.360buyimg.com/??jdf/lib/jquery-1.6.4.js,jdf/1.0.0/ui/ui/1.0.0/ui.js
http://misc.360buyimg.com/??product/home/1.0.0/js/init.js,jdf/1.0.0/unit/wl/1.0.0/wl.js

于是乎在网上一搜,大概了解实现方法,于是自己也配置一下:

系统环境:

1
2
CentOS release 6.2 (Final)
Linux version 2.6.32-220.el6.x86_64

nginx和http_concat模块安装:

1
2
3
4
5
6
7
8
9
cd /usr/local/src/
wget http://nginx.org/download/nginx-1.4.2.tar.gz
wget https://github.com/alibaba/nginx-http-concat/archive/master.zip -O nginx-http-concat-master.zip
unzip nginx-http-concat-master.zip
tar -xzvf nginx-1.4.2.tar.gz
cd nginx-1.4.2/
./configure --prefix=/usr/local/nginx-1.4.2 --with-http_stub_status_module --add-module=../nginx-http-concat-master
make
make install

如果出现找不到PCRE库,下载地址:http://sourceforge.net/projects/pcre/files/pcre/
下载文件放到/usr/local/src/后:

1
2
3
4
5
tar -xzvf pcre-8.37.tar.gz
cd pcre-8.37/
./configure
make
make install

检查nginx的配置文件:

1
/usr/local/nginx-1.4.2/sbin/nginx -t

指定配置文件启动nginx:

1
/usr/local/nginx-1.4.2/sbin/nginx -c /usr/local/nginx-1.4.2/conf/nginx.conf

如果出现错误: error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory,
解决办法:

1
2
cd /lib64
ln -s libpcre.so.0.0.1 libpcre.so.1

重新执行启动命令,访问ok!
接下来修改配置文件:

1
vim /usr/local/nginx-1.4.2/conf/nginx.conf

修改配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 server {
listen 8080;
server_name localhost;
root /var/www/html;
#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root /var/www/html;
index index.html index.htm;
}

location /static/{
concat on;
concat_max_files 20;
concat_unique off;
}
...
}

然后重新启动nginx服务:

1
2
/usr/local/nginx-1.4.2/sbin/nginx -s stop
/usr/local/nginx-1.4.2/sbin/nginx -c /usr/local/nginx-1.4.2/conf/nginx.conf

当然也可以热启动:

1
/usr/local/nginx-1.4.2/sbin/nginx -s reload

制作测试文件,添加一个index.html页面,并添加两个js文件:

1
2
3
4
5
//默认加载写法
<!--script type="text/javascript" src="/static/jquery-1.8.3.js"></script>
<script type="text/javascript" src="/static/debug.js"></script-->

//一次加载多个文件的写法
<script type="text/javascript" src="/static/??jquery-1.8.3.js,debug.js" ></script>

浏览器打开页面,查看网络加载,文件加载成功,并且合并成了一个!

感谢您的阅读,有不足之处请在评论为我指出!

参考资料

[1]:nginx js、css多个请求合并为一个请求(concat模块)
[2]:使用Tengine concat模块合并多个CSS,JS 请求

版权声明:本文为博主原创文章,未经博主允许不得转载。本文地址 http://yangyuji.github.io/2015/07/24/nginx-js-concat/