Nginx如何配置静态文件过期时间
与Apache使用expires_module (shared)模块配置静态缓存不同,Nginx使用修改对应虚拟主机配置文件即可。
一、编辑虚拟主机配置文件
[root@daixuan nginx_log]# cd /usr/local/nginx/conf/vhosts/
[root@daixuan vhosts]# vim test.conf //jpg15天过期,js,css2小时过期
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
access_log off;
expires 15d;
}
location ~ .*\.(js|css) {
access_log off;
expires 2h;
}
[root@daixuan vhosts]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@daixuan vhosts]# /etc/init.d/nginx reload
重新载入 Nginx: [确定]
[root@daixuan vhosts]# service nginx restart
停止 Nginx: [确定]
正在启动 Nginx: [确定]
二、测试
[root@daixuan vhosts]# curl -x127.0.0.1:80 'http://www.test.com/static/image/common/security.png' -I
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Wed, 13 Jan 2016 01:33:31 GMT
Content-Type: image/png
Content-Length: 2203
Last-Modified: Tue, 09 Jun 2015 02:21:10 GMT
Connection: keep-alive
ETag: "55764d96-89b"
Expires: Thu, 28 Jan 2016 01:33:31 GMT
Cache-Control: max-age=1296000 //1296000s就是15天
Accept-Ranges: bytes
[root@daixuan vhosts]# curl -x127.0.0.1:80 'http://www.test.com/static/js/home.js?E00' -I
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Wed, 13 Jan 2016 01:32:53 GMT
Content-Type: application/javascript
Content-Length: 33801
Last-Modified: Tue, 09 Jun 2015 02:21:10 GMT
Connection: keep-alive
ETag: "55764d96-8409"
Expires: Wed, 13 Jan 2016 03:32:53 GMT
Cache-Control: max-age=7200 //7200s就是2小时
Accept-Ranges: bytes