nginx 如何在配置文件给静态文件添加缓存

2024-5-23 杜世伟

在 Nginx 中为静态文件添加缓存可以通过设置响应头来实现。这可以通过在 Nginx 配置文件中使用 expires 指令来完成。以下是一个示例配置,展示了如何为特定类型的静态文件(如图像、CSS、JavaScript 文件等)设置缓存头。

假设你的 Nginx 配置文件路径是 /etc/nginx/nginx.conf,你可以在其中添加或修改 server 块来包含缓存配置:

http {
    # 其他全局配置

    server {
        listen 80;
        server_name example.com;

        root /var/www/html;

        location / {
            try_files $uri $uri/ =404;
        }

        # 为图像文件设置缓存
        location ~* \.(jpg|jpeg|png|gif|ico|bmp|webp)$ {
            expires 30d;
            add_header Cache-Control "public, no-transform";
        }

        # 为CSS和JavaScript文件设置缓存
        location ~* \.(css|js)$ {
            expires 7d;
            add_header Cache-Control "public, no-transform";
        }

        # 为字体文件设置缓存
        location ~* \.(woff|woff2|ttf|otf|eot)$ {
            expires 30d;
            add_header Cache-Control "public, no-transform";
        }

        # 为SVG文件设置缓存
        location ~* \.(svg|svgz)$ {
            expires 30d;
            add_header Cache-Control "public, no-transform";
        }

        # 其他静态文件
        location ~* \.(html|htm)$ {
            expires 1h;
            add_header Cache-Control "public, no-transform";
        }

        # 其他配置...
    }
}

在上述配置中:

expires 指令用于设置过期时间,30d 表示30天,7d 表示7天,1h 表示1小时。
add_header Cache-Control 指令用于设置 Cache-Control 响应头,public, no-transform 表示允许所有缓存,且在缓存时不进行转换。

sudo nginx -s reload

这样,Nginx 将为匹配的静态文件添加缓存头,帮助浏览器和中间缓存服务器更好地缓存这些文件,从而提高性能。

标签: nginx expires

评论(0) 浏览(4585)

Powered by emlog 沪ICP备2023034538号-1