引言
最近在优化网站性能时,发现很多静态资源(比如图片、css 文件等)每次都会从服务器重新加载,这不仅浪费了带宽,还增加了 服务器的负载。为了解决这个问题,我研究了一下如何在 nginx 中为静态资源配置缓存时间,让客户端能更高效地利用缓存,从而提升访问速度。下面是我的配置过程,分享给有需要的小伙伴。
1. 配置网页缓存时间
目的
为静态资源(如图片、css 文件等)设置缓存时间,减少重复请求,提高访问速度。
操作步骤
- 编辑 nginx 主配置文件:
cd /usr/local/nginx/conf/ vim nginx.conf
- 在
http
块中添加以下内容:
http { ... location / { root html; index index.html index.htm; } location ~ \.(gif|jpg|jpeg|png|bmp|ico)$ { root html; expires 1d; # 设置缓存时间为一天 } ... }
- 测试配置文件语法是否正确:
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
- 重启 nginx 服务:
systemctl restart nginx
测试步骤
使用 curl
命令带上 -i
参数,查看静态资源的响应头。例如:
再次运行相同的 curl
命令,检查是否返回相同的缓存参数。如果配置正确,浏览器或客户端将在缓存有效期内直接使用缓存数据,而不会重复请求服务器。
[root@localhost ~]# curl -i 127.0.0.1 http/1.1 200 ok server: nginx date: fri, 20 dec 2024 06:59:17 gmt content-type: text/html content-length: 612 last-modified: fri, 20 dec 2024 06:43:28 gmt connection: keep-alive etag: "67651210-264" expires: sat, 21 dec 2024 06:59:17 gmt cache-control: max-age=86400 accept-ranges: bytes cache-control: max-age=86400 expires: <具体的日期时间>
说明:
max-age=86400
表示缓存时间为 86400 秒(即 1 天)。- 客户端将在缓存有效期内直接使用缓存数据,而不会重复请求服务器。
总结
通过为静态资源设置缓存时间,服务器的压力得到了有效缓解,客户端也能更快地加载网页,用户体验自然也就提升了。这种配置简单易行,却能带来显著的效果。如果你也在优化网站性能,不妨试试这个方法。
到此这篇关于nginx为静态资源配置缓存时间的操作步骤的文章就介绍到这了,更多相关nginx静态资源配置缓存时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论