首先了解一下 nginx-http-concat,他是一個(gè)淘寶的開(kāi)源Nginx模塊,是一個(gè)能把多個(gè)CSS和JS合并成一個(gè)請(qǐng)求的Nginx模塊,對(duì)于Web性能優(yōu)化非常有意義。
Github地址:https://github.com/alibaba/nginx-http-concat,
先看看淘寶用起來(lái)是什么樣的,訪(fǎng)問(wèn)淘寶網(wǎng)主頁(yè),查看源代碼可以看到類(lèi)似的這樣的style/script鏈接
<link rel="stylesheet" href="//g.tbcdn.cn/??tb/global/2.1.6/global-min.css,tb/tb-fp/1.2.3/style-min.css?t=20130912">
<script src="//g.tbcdn.cn/??kissy/k/1.3.1/seed-min.js,tb/global/2.1.6/global-min.js,tb/tb-fp/1.2.3/core-min.js?t=20130912"></script>
是不是很神奇,只需要一個(gè)請(qǐng)求,就可以把需要的CSS/JS文件通過(guò)合并的方式把他輸出成一個(gè)文件(注意,雖然淘寶有min格式的文件,但是這里它僅僅是合并多個(gè)文件,而不會(huì)自動(dòng)的對(duì)其壓縮打包文件)
首先我們先從Git上下載安裝它
#下載
$ git clone git://github.com/alibaba/nginx-http-concat.git
#移動(dòng)目錄
$ mv nginx-http-concat /usr/local/src/nginx-http-concat
查看原始Nginx版本,這很重要,因?yàn)槲覀冃枰惭b同一個(gè)版本來(lái)升級(jí)數(shù)據(jù)
#查看版本號(hào)以及配置信息(目錄/模塊)
$ /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.3.1
TLS SNI support disabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module
根據(jù)查詢(xún)的版本號(hào)下載對(duì)應(yīng)版本的nginx,可以到官方下載指定版本:http://nginx.org/download/
我這里使用的是1.3.1
$ wget nginx-1.3.1.tar.gz
$ tar zxvf nginx-1.3.1.tar.gz
$ cd nginx-1.3.1
#根據(jù)上面-V的信息 加入concat模塊所在路徑 (--add-module=/usr/local/src/nginx-http-concat) 進(jìn)行編譯
$ ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --add-module=/usr/local/src/nginx-http-concat
make之前備份配置文件,防止意外
$ cp -r /usr/local/nginx/conf /root/nginxconf
#編譯安裝
$ make && make install
接下來(lái)就是配置你的靜態(tài)服務(wù)器conf文件
server {
listen 80;
server_name static.dexphp.loc;
index index.html index.htm;
root /mnt/siteroot/static.dexphp.com;
location /static/css/ {
concat on;
concat_max_files 20; //最大合并文件數(shù)量是20個(gè)
}
location /status {
stub_status on;
access_log off;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js)$ {
expires off;
}
error_log /mnt/siteroot/wwwlogs/static.dexphp.loc.error.log;
access_log /mnt/siteroot/wwwlogs/static.dexphp.loc.access.log;
}