> For the complete documentation index, see [llms.txt](https://yangsx95.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yangsx95.gitbook.io/notes/distributed/web-fu-wu-qi/nginx/huan-cun.md).

# 缓存

缓存用于减轻后端服务压力。缓存可以分为 服务端缓存(redis，ehcache)、客户端缓存(localstorage)、代理缓存(nginx)。nginx的缓存服务就是代理缓存。

![1556159422900](/files/pvrNKZiIRLSg2wv2tPy5)

## proxy\_cache

proxy\_cache的配置同样位于proxy代理模块，相关配置比较多，一下是较为常用的几个配置：

```nginx
# 配置缓存文件 path路径
Syntax:	proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
Default:	—
Context:	http

# 开启代理缓存，zone代表哪个path
Syntax:	proxy_cache zone | off;
Default:	proxy_cache off;
Context:	http, server, location

# 缓存有效期配置
Syntax:	proxy_cache_valid [code ...] time;
Default:	—
Context:	http, server, location

# 缓存维度配置，即配置key
Syntax:	proxy_cache_key string;
Default:	proxy_cache_key $scheme$proxy_host$request_uri;
Context:	http, server, location
```

## 示例配置

```nginx
upstream blog {    
    server 192.168.0.159:8080;
    server 192.168.0.159:8081; 
    server 192.168.0.159:8082; 
}

# /opt/app/cache 缓存存储路径
# levels 按照目录进行归并和分级，1:2 代表两层目录进行分级
# keys_zone 定义开辟zone空间的名称，以供下面引用，10m代表大小，1m大约可以存放8000个key
# max_size 缓存目录最大多大，用满之后就会触发淘汰规则 
# inactive=60m 超过60分钟的未被访问的缓存空间，此缓存就会被移除
# use_temp_path 临时路径，建议关闭，会有不必要的性能损耗
proxy_cache_path /opt/app/cache levels=1:2 keys_zone=blog_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name localhost;
    location / {
        # 开启缓存，使用blog_cache zone
        proxy_cache blog_cache;
        proxy_pass http://blog;
        # 针对200和304请求进行缓存，缓存有效期为12h
        proxy_cache_valid 200 304 12h;
        # 其他状态的缓存有效期配置为10分钟
        proxy_cache_valid any 10m;
        # 维度配置
        proxy_cache_key $host$uri$is_args$args;
        # 增加头信息，告诉客户端缓存是否被命中
        add_header Nginx-Cache "$upstream_cache_status";
        
        # 当某台服务器出现error、timout、500状态等情况时，就跳过此台服务器
        proxy_next_upstream error timout invalid_header http_500 http_502 http_503 http_504;
        include proxy_params;
    }
}
```

## 如何清除缓存

* 清空对应缓存目录：`rm -rf 缓存目录内容`，无法清空指定的url缓存
* 使用第三方模块`ngx_cache_purge`

## 如何让部分页面不缓存

```nginx
# 定义不将响应保存到缓存的条件。如果字符串参数的至少一个值不为空且不等于“0”，则不会保存响应
Syntax:	proxy_no_cache string ...;
Default:	—
Context:	http, server, location
```

**示例：**

```nginx
# 以下配置在server块中
# 如果是登录、注册、密码重置等页面，就设置cookie nocachekey为1
if ($request_uri ~ ^/(url3|login|register|password\/reset)) {
    set $cookie_nocache 1;
}

location / {
    proxy_cache off;
        proxy_pass http://imooc;
        proxy_cache_valid 200 304 12h;
        proxy_cache_valid any 10m;
        proxy_cache_key $host$uri$is_args$args;
        add_header  Nginx-Cache "$upstream_cache_status";  
    	# 生效nocache
    	proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
    	proxy_no_cache $http_pragma $http_authorization;
    
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        include proxy_params;
}
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pragma $http_authorization;
```

## 分片请求

1.9版本增加了`slice size`提供了大文件分片请求的支持：

```nginx
Syntax: slice size;
Default: slice 0;
Context: http, server, location
```

1. 前端请求大文件，nginx去服务端获取文件大小
2. 根据定义的slice片的大小，nginx进行切片，分为多个请求，请求服务端

**优势**：每个子请求收到的数据都是一个独立的文件，其他请求不会受影响

**缺点**：如果slice大小设置的不合理（slice太小），会导致文件描述符耗尽等情况
