Nginx Variable Cache Time

1.3k views Asked by At

I'm currently working with fastcgi_cache and wanted to pass a variable to fastcgi_cache_valid so I could have variable amount of cache time depending on the file. But it seems that it will not accept a variable.

I tried the following:

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;

But I receieved the following errors:

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

There are 1 answers

0
phoenixstudio On

fastcgi_cache_valid does not accept variable but there is a work around if you have only two options cached and not-cached.

In this example we want cached.php to return the cached version, and the non-cached version if the url contains params. meaning cached.php will always reaturn the cached version and cached.php?id=1 will always return the non-cached version.

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";
}

This the content of cached.php used for test

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

This is the results if tests using 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 is used only for debuging and it is not necessary.