nginx中浏览器缓存相关指令介绍

403 阅读1分钟

「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

nginx中浏览器缓存相关指令介绍

Nginx需要进行缓存相关设置,nginx如何对缓存进行优化配置,那么就需要用到如下的缓存相关指令, nginx默认是支持这些指令的,不需要单独安装指定的模块:

expires指令

expires:使用该指令用来控制页面缓存的作用。可以通过该指令控制HTTP应答中的“Expires"和”Cache-Control"

语法expires [modified] time
expires epoch | max | off;
默认值expires off;
位置http,server,location

time:可以整数也可以是负数,指定过期时间,如果是负数,CacheControl则为no-cache,如果为整数或0,则Cache-Control的值为max

age=time;

epoch: 指定Expires的值为'1 January,1970,00:00:01 GMT'(1970-01-0100:00:00),Cache-Control的值no-cache

max:指定Expires的值为'31 December2037 23:59:59GMT' (2037-12-31 23:59:59) ,Cache-Control的值为10年。

off:默认不缓存。 例子:

location ~ .*\.(html|js|css|png)${
		expires max;
}

add_header指令

add_header指令是用来添加指定的响应头和响应值。

语法add_header name value [always];
默认值---
位置http,server,location

Cache-Control作为响应头信息,可以设置如下值:

缓存响应指令:

Cache-control: must-revalidate 
Cache-control: no-cache 
Cache-control: no-store 
Cache-control: no-transform 
Cache-control: public 
Cache-control: private 
Cache-control: proxy-revalidate 
Cache-Control: max-age=<seconds> 
Cache-control: s-maxage=<seconds> 
语法说明
must-revalidate可缓存但必须再向源服务器进行确认
no-cache缓存前必须确认其有效性
no-store不缓存请求或响应的任何内容
no-transform代理不可更改媒体类型
public可向任意方提供响应的缓存
private仅向特定用户返回响应
proxy-revalidate要求中间缓存服务器对缓存的响应有效性再进行确认
max-age=<秒>响应最大Age值
s-maxage=<秒>公共缓存服务器响应的最大Age值

例子:

location ~ .*\.(html|js|css|png)${
		expires max;
    add_header Cache-Control no-store
}