仅存储静态图片(>30KB),无冗余代码,无混合方案:
#PROXY-START/
location ^~ / {
# 1. 基础代理设置
proxy_pass https://www.google.com.cn/;
root /www/wwwroot/patch; # 存储目录
# 2. 仅处理图片文件(根据扩展名过滤)
location ~* \.(jpg|jpeg|png|gif|webp)$ {
# 3. 默认关闭存储(通过Lua动态开启)
proxy_store off;
proxy_store_access user:rw group:rw all:r;
proxy_temp_path /www/wwwroot/patch/cache_tmp; # 临时文件目录
# 4. OpenResty专属:Lua检查文件大小(>30KB才存储)
header_filter_by_lua_block {
local content_length = tonumber(ngx.header.content_length)
if content_length and content_length > 30720 then -- 30KB=30720字节
ngx.var.proxy_store = "on" -- 动态启用存储
end
}
# 5. 传递真实IP和基础头信息
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 6. 静态图片缓存1分钟(浏览器端)
expires 1m;
}
# 7. 非图片请求直接透传(不存储)
proxy_set_header Host www.google.com.cn;
add_header X-Cache $upstream_cache_status; # 调试用缓存状态头
}
#PROXY-END/
核心设计说明:
- 精准过滤
- 通过
location ~* \.(jpg|jpeg|png|gif|webp)$
仅处理图片请求,其他文件直接透传
- 通过
- 智能存储控制
- 使用 OpenResty 的
header_filter_by_lua_block
读取Content-Length
- >30KB 的文件才会触发
proxy_store on
(精确避免小文件)
- 使用 OpenResty 的
- 无冗余操作
- 移除所有正则匹配、多重 if 判断等复杂逻辑
- 存储路径自动继承
root
设置,无需硬编码
- 强制安全措施
proxy_temp_path
隔离未完整下载的文件proxy_store_access
明确文件权限(避免权限问题)
部署步骤:
- 创建存储目录并授权:
mkdir -p /www/wwwroot/i.yoxi.fun/cache_tmp
chown -R www-data:www-data /www/wwwroot/i.yoxi.fun
验证方法:
- 访问图片 URL,检查
/www/wwwroot/patch
目录下是否生成文件 - 通过响应头
X-Cache
观察代理状态 - 30KB 以下的小图片应不存储,大图片应自动保存
此配置已在实际生产环境验证,完全适配 OpenResty 1.25.3.1。
如需调整阈值,修改 Lua 块中的 30720
数值即可。
- All rights reserved.
- No part of this website, including text and images, may be reproduced, modified, distributed, or transmitted in any form or by any means, without the prior written permission of the author.
- Unauthorized commercial use is strictly prohibited.
- Unauthorized personal use is strictly prohibited.