Nginx 笔记与总结(14)expires 缓存设置

设置缓存,可以提高网站性能。

当网站的部分内容,比如新闻站的图片,一旦发布就不太可能发生更改,此时需要用户在访问一次页面之后,把该页面的图片缓存在用户的浏览器端一段时间,就可以用到 nginx 的 expires 设置。

 

expires 的语法参见:http://nginx.org/en/docs/http/ngx_http_core_module.html

location = /images/default.gif {
    expires 30s; # 30m:30 分钟,2h:2 小时,30d:30 天
}

expires 的上下文包括 location、if in location

 

【例】

访问 http://192.168.254.100/

图片 nginx.png 的响应状态是 200 ok

此时图片的 http 头信息:

 

再次刷新该页面

图片 nginx.png 的响应状态是 304 Not Modified,即来自浏览器缓存

此时图片的的 http 头信息:

 

虽然图片该次是从浏览器缓存中读取,但是浏览器仍然像服务器发出了一次 http 请求

如果要实现在一定时间内,浏览器不需要向服务器发送 http 请求,而直接从本地缓存中读取图片,可以在 nginx.conf 中进行配置:

[root@localhost nginx]# vim conf/nginx.conf

nginx.conf(添加 location 段 或者 修改 location ~ image ):

        location ~ image {
            root /var/www/;
expires 1d; index index.html; }

平滑重启 nginx

 

强刷(ctrl+f5)该页面,此时图片的 http 响应信息:

86400 是 1 天的秒数。

 

再次刷新该页面(按浏览器的刷新按钮):

 

 

在地址栏回车刷新页面:

 没有产生实际请求。

 

在 chrome 浏览器下,通过地址栏回车刷新页面时的 http 响应信息:

 

 from cache 表名没有产生实际请求。

 

修改 location ~ image 或者 添加 location,使缓存图片不仅限于 image 文件夹,而是网站中所有的 png|jpg|jpeg|gif (不区分大小写)图片都进行缓存设置:

        location ~* \.(jpg|jpeg|png|gif){
            expires 1d;
        }

平滑重启 nginx。

 

验证:访问 ecshop 目录下的某个图片

 没有产生实际请求。

 

点击浏览器刷新按钮,查看该图片的 http 响应头信息:

说明此次 location 配置成功。

 

posted @ 2015-08-19 23:25  nemo20  阅读(7227)  评论(0编辑  收藏  举报
访客数:AmazingCounters.com
2016/05/17 起统计