server {
# 监听端口
listen 80;
# 域名
server_name domain.com; # 图片访问的域名
# 这个路径是基于框架的统一文件访问前缀
location /api/static/file { # 这里/api/static/file是图片访问的基础路径
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
set $encoded_filename "";
if ($request_uri ~* "^/api/static/file/(.*)\?.*$") {
# filename解码,避免重复URL编码
set_unescape_uri $decoded_filename $1;
# 替换filename中的@为%40,否则imgproxy会认为@是分隔符
set_by_lua_block $encoded_filename {
local filename = ngx.var.decoded_filename
local encoded = string.gsub(filename, "@", "%%40")
return encoded
}
}
# 根据路径参数p=true来判断是否进行转发
if ($arg_p = 'true') {
# 将图片处理请求根据imgproxy的规则进行路径重写
rewrite ^(.*)$ /signature/resize:$arg_f:$arg_w:$arg_h:0/plain/local:///$encoded_filename@$arg_t break;
# 转发给imgproxy进行处理
proxy_pass http://127.0.0.1:8081;
expires max;
# 基于浏览器的缓存 携带此请求头浏览器会缓存图片
add_header Cache-Control "public, no-transform";
}
# 没有携带参数p则直接请求原图 10001为后端服务的路径
proxy_pass http://127.0.0.1:10001;
# 启用基于nginx的代理缓存 指定缓存名称
proxy_cache imgproxy;
# 配置缓存key的规则
proxy_cache_key $scheme$proxy_host$uri$is_args$args;
# 基于http状态码来配置缓存的过期时间 这里设置为30天
proxy_cache_valid 200 304 302 30d;
expires max;
add_header Cache-Control "public, no-transform";
}
}