问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Nginx中如何为静态资源配置缓存时间,提升网页访问速度

创作时间:
作者:
@小白创作中心

Nginx中如何为静态资源配置缓存时间,提升网页访问速度

引用
CSDN
1.
https://blog.csdn.net/jxjdhdnd/article/details/145144250

本文将介绍如何在Nginx中为静态资源配置缓存时间,以提升网站访问速度和性能。通过设置合理的缓存策略,可以有效减少服务器负载,提高用户访问体验。

配置网页缓存时间

目的

为静态资源(如图片、CSS文件等)设置缓存时间,减少重复请求,提高访问速度。

操作步骤

  1. 编辑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; # 设置缓存时间为一天
        }
        ...
    }
    
  2. 测试配置文件语法是否正确:

    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
    
  3. 重启Nginx服务:

    systemctl restart nginx
    

测试步骤

使用curl命令带上-I参数,查看静态资源的响应头。例如:

[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天)。
  • 客户端将在缓存有效期内直接使用缓存数据,而不会重复请求服务器。

总结

通过为静态资源设置缓存时间,服务器的压力得到了有效缓解,客户端也能更快地加载网页,用户体验自然也就提升了。这种配置简单易行,却能带来显著的效果。如果你也在优化网站性能,不妨试试这个方法。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号