首页 > 解决方案 > 利用浏览器缓存 - 带有 CDN 的 nginx

问题描述

我正在测试我的网站pingdomhttps ://tools.pingdom.com/#!/dCLQGc/https://stagingreport.daytwo.com

并在利用浏览器缓存方面获得低分: 在此处输入图像描述

使用以下配置从 nginx 服务器提供的所有静态文件

server {
   listen 80;

    gzip on;
    gzip_vary on;
    gzip_types    text/plain application/javascript application/x-javascript text/javascript text/xml text/css;


    access_log  /var/log/nginx/access.log;
    error_log   /var/log/nginx/error.log;

    root /usr/share/nginx/html;
    index index.html index.htm;

    location / {
        if ($http_x_forwarded_proto = "http") {
            return 301 https://$host$request_uri;
        }

        try_files $uri $uri/ /index.html;
    }


}

因为我使用的是谷歌云 CDN,所以我没有在服务器上设置任何缓存配置。

为了获得更高的性能分数,我应该更改 nginx 配置中的某些内容吗?

标签: angularperformancenginxgoogle-cloud-platformcdn

解决方案


根据下面提到的缓存细节,您可能需要相应地配置 nginx:

只有满足以下所有条件时,才能将响应存储在 Cloud CDN 缓存中:

它由启用了 Cloud CDN 的后端服务或后端存储桶提供服务。

它是对 GET 请求的响应。

其状态码为 200、203、206、300、301、302、307 或 410。

它有一个 Content-Length 标头或一个 Transfer-Encoding 标头。

它有一个 Cache-Control: 公共标头。

它有一个 Cache-Control: s-maxage、Cache-Control: max-age 或 Expires 标头。

它具有 Content-Length、Content-Range 或 Transfer-Encoding 标头。

它的大小小于或等于最大大小。

对于后端存储桶,您可以通过将对象标记为公开共享来满足这些要求。

还有一些检查会阻止缓存响应。如果以下任何一项为真,则不会缓存响应:

它有一个 Set-Cookie 标头。

它有一个 Vary 标头,其值不是 Accept、Accept-Encoding 或 Origin。

它有一个 Cache-Control: no-store、no-cache 或 private 指令。

相应的请求有一个 Cache-Control: no-store 指令。


推荐阅读