Nginx服务优化(三)配置网页缓存时间

本文详细介绍如何在Nginx中配置网页缓存时间,通过修改配置文件中的http、server或location段,设置静态资源如图片的缓存时间为一天,以加速网页加载速度并减少服务器负担。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置Nginx网页缓存时间

当Nginx将网页数据返回给客户端后,可设置缓存的时间,以方便在日后进行相同内容的请求时直接返回,避免重复请求,加快了访问速度。一般针对静态网页设置,对动态网页不设置缓存时间。可在Windows客户端中使用fiddler查看网页缓存时间。

设置方法

可修改配置文件,在http段、或者server段、 或者location段加入对特定内容的过期参数

1.将图片复制到站点目录

[root@localhost nginx-1.12.2]# cd /mnt/tools/
[root@localhost tools]# ls
awstats-7.6.tar.gz                fiddler.exe                jdk-8u191-windows-x64.zip  LNMP         zhuang.mp4
cronolog-1.6.2-14.el7.x86_64.rpm  forbid.png                 john-1.8.0.tar.gz          picture.jpg
extundelete-0.2.4.tar.bz2         intellijideahahau2018.rar  LAMP-C7                    yuan.mp4
[root@localhost tools]# cp picture.jpg /usr/local/nginx/html/    //复制图片
[root@localhost tools]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html  index.html  picture.jpg
[root@localhost html]# 

2.在首页文件添加引用图片

[root@localhost html]# vim index.html

<h1>Welcome to nginx!</h1>
<img src="picture.jpg"/>   //添加


[root@localhost html]# systemctl stop firewalld.service    //关闭防火墙
[root@localhost html]# setenforce 0   //关闭增强性安全功能
[root@localhost html]# 

3.用win10虚拟机访问nginx服务,并抓包(未开启缓存)

4.在nginx配置文件中添加缓存模块

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf

        location ~ \.(gif|jepg|jpg|ico|bmp|png)$ {   //添加缓存
            root html;   //站点
            expires 1d;   //缓存一天
        }
[root@localhost html]# service nginx restart    //重启服务
[root@localhost html]#

5.再次用win10虚拟机访问nginx服务,抓包(开启缓存)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值