Nginx 的 expires 指令是核心功能,无需安装模块,源自默认启用的 http_headers 模块;必须在 location 块中配置,推荐按静态资源后缀或目录匹配并设置合理缓存时间,同时正确设置 Cache-Control 头。
不需要单独配置或安装“expires 模块”——expires 指令是 Nginx 核心功能,源码安装后默认就可用,无需额外编译选项或第三方模块。
expires 属于 Nginx 的 http_headers 模块(ngx_http_headers_module),该模块在源码编译时默认启用。只要你在 configure 阶段没显式用 --without-http_headers_module 禁用它,就一定支持 expires 指令。
验证方式:安装完成后运行 nginx -V 2>&1 | grep -o with-http_headers_module,若输出该字符串,说明已内置。
在你的站点 server 块中,用精准 location 匹配静态资源,然后写 expires:
location ~* .(js|css|png|jpg|jpeg|gif|woff2|ttf|eot|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
location ^~ /static/ {
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
location ~* .html$ {
expires epoch;
add_header Cache-Control "no-cache, must-revalidate, max-age=0";
}
"public, immutable" 而非分两次加改完配置后执行三步:
nginx -t 检查语法nginx -s reload 重载配置curl -I https://yoursite/style.css 查看响应头,确认同时存在:Expires: Wed, 31 Dec 2037 23:55:55 GMT
Cache-Control: public, immutable, max-age=31536000