Skip to content

Instantly share code, notes, and snippets.

@dreamlu
Last active February 8, 2025 10:04
Show Gist options
  • Save dreamlu/ea25878b7cccc64a7b6b2864f1af4b7e to your computer and use it in GitHub Desktop.
Save dreamlu/ea25878b7cccc64a7b6b2864f1af4b7e to your computer and use it in GitHub Desktop.
nginx 缓存后端接口
http {
# 定义缓存存储路径及相关参数,创建目录:/var/cache/nginx/api_cache
proxy_cache_path /var/cache/nginx/api_cache levels=1:2 keys_zone=api_cache:10m
max_size=1g inactive=60m use_temp_path=off;
...
server {
listen 80;
server_name example.com;
# 针对分页 API 接口配置缓存
location /api/data {
# 将请求转发到后端服务器(假设后端 upstream 名称为 backend)
proxy_pass http://backend;
# 启用缓存并指定缓存区域
proxy_cache api_cache;
# 定义缓存键,包含请求的 scheme、请求方法、host 与完整 URI(包含查询参数)
proxy_cache_key "$scheme$request_method$host$request_uri";
# 设置响应缓存时间,例如200状态的响应缓存 10 分钟
proxy_cache_valid 200 10m;
# 为调试添加缓存状态的响应头 (如 HIT/MISS)
add_header X-Cache-Status $upstream_cache_status;
# 针对后端禁止缓存,强制缓存
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
}
}
}
# 验证
#查看响应头中的 X-Cache-Status:
#HIT:缓存命中
#MISS:缓存未命中
#BYPASS:缓存被绕过
#EXPIRED:缓存已过期
#UPDATING:缓存正在更新
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment