前端 nginx 使用反向代理与我的后端一起工作,我想只缓存特定文件类型,比如图像文件, 但它似乎根本不起作用,$no_cache 总是输出默认值“proxy”,当我访问图片类文件时本应该输出“0”
map $upstream_http_content_type $no_cache {
  default proxy;
  "~*image"  0;
}
proxy_store on;
proxy_temp_path /tmp/ngx_cache;
proxy_cache_path /tmp/ngx_cache/pcache levels=1:2 use_temp_path=on keys_zone=pcache:10m inactive=14d max_size=3g;
log_format upstreamlog '$server_addr:$host:$server_port $remote_addr:$remote_port $remote_user [$time_local] '
                         '"$request" $status $request_length $body_bytes_sent [$request_time] '
                         '"$http_referer" "$http_user_agent" "$http_x_forwarded_for" - '
                        'upstream: $upstream_addr - $upstream_status - upstream_response_time: $upstream_response_time $upstream_http_content_type $skip_cache : $no_cache';
server{
.....
if ($skip_cache = false){
    set $skip_cache 0;
}
if ($no_cache = false){
    set $no_cache 0;
}
if ($request_method = POST) {
    set $skip_cache 1;
}  
if ($query_string != "") {
    set $skip_cache 1;
}  
if ($http_cache_control ~* "private") {
    set $skip_cache 1;
}  
if ($upstream_http_cache_control ~* "private") {
    set $skip_cache 1;
}
 location / {
   proxy_cache_key "$http_host$uri$is_args$args";
   proxy_cache pcache;
   add_header X-Cache-Status $upstream_cache_status;
   proxy_cache_bypass $http_pragma $http_authorization $skip_cache;
   proxy_no_cache $http_pragma $http_authorization $skip_cache $no_cache;
   proxy_pass http://$backend;
   access_log /dev/stdout upstreamlog;
 }
}
curl 测试结果
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 30 Oct 2022 17:22:56 GMT
Content-Type: image/jpeg
Content-Length: 56769
Connection: keep-alive
Last-Modified: Tue, 19 Jul 2022 03:27:34 GMT
ETag: "62d624a6-ddc1"
Cache-Control: public, max-age=604800, s-maxage=1209600, stale-if-error=400
X-Cache-Status: MISS
Accept-Ranges: bytes
日志里显示输出的$no_cache始终是 proxy
为什么$upstream_http_content_type没有正确匹配到“0”值呢?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.