Nginx可变缓存时间

时间:2015-06-18 18:43:31

标签: nginx fastcgi

我目前正在使用fastcgi_cache并希望将变量传递给fastcgi_cache_valid,因此根据文件的不同,我可能会有不同的缓存时间。但它似乎不接受变量。

我尝试了以下内容:

set $cache_time 15s;
fastcgi_cache_valid 200 ${cache_time};
fastcgi_cache_valid 200 $cache_time;


set $cache_time "15s";
fastcgi_cache_valid 200 ${cache_time};
fastcgi_cache_valid 200 $cache_time;


set $cache_time 15;
fastcgi_cache_valid 200 ${cache_time}s;
fastcgi_cache_valid 200 $cache_time;

但我收到了以下错误:

nginx: [emerg] invalid time value "$cache_time" in /etc/nginx/conf.d/www.com.conf:118

nginx: [emerg] directive "fastcgi_cache_valid" is not terminated by ";" in /etc/nginx/conf.d/www.com.conf:118

1 个答案:

答案 0 :(得分:0)


fastcgi_cache_valid 不接受变量,但如果您只有两个选项 cachednot-cached,则有一种变通方法。

在这个例子中,我们希望 cached.php 返回缓存版本,如果 url 包含参数,则返回非缓存版本。意味着 cached.php 将始终返回缓存版本,而 cached.php?id=1 将始终返回非缓存版本。

location = /cached.php {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
  set $disable_cache 1;
  if ( $request_uri = "/cached.php" ){
    set $disable_cache 0;
  }
  fastcgi_cache phpcache;
  fastcgi_cache_valid 200 1h;
  fastcgi_cache_methods GET HEAD;
  fastcgi_cache_bypass $disable_cache;
  fastcgi_no_cache $disable_cache;
  add_header X-Is-Cached "Cache disabled $disable_cache";
}

这是用于测试的cached.php的内容

<?php echo "The time is " . date("h:i:sa")."\n";?>

这是使用 curl 测试的结果

curl --head "http://www.example.com/cached.php"

 HTTP/1.1 200 OK
 Server: nginx/1.14.0 (Ubuntu)
 Date: Thu, 31 Dec 2020 17:07:55 GMT
 Content-Type: text/html; charset=UTF-8
 Connection: keep-alive
 X-Fastcgi-Cache: HIT
 X-Is-Cached: Cache disabled 0

curl --head "http://www.example.com/cached.php?id=1"

 HTTP/1.1 200 OK
 Server: nginx/1.14.0 (Ubuntu)
 Date: Thu, 31 Dec 2020 17:09:15 GMT
 Content-Type: text/html; charset=UTF-8
 Connection: keep-alive
 X-Fastcgi-Cache: BYPASS
 X-Is-Cached: Cache disabled 1

X-Is-Cached 仅用于调试,没有必要。