rynop
rynop

Reputation: 53559

nginx: add conditional expires header to fastcgi_cache response

When using nginx fastcgi_cache, I cache HTTP 200 responses longer than I do any other HTTP code. I want to be able to conditionally set the expires header based on this code.

For example:

fastcgi_cache_valid   200 302  5m;
fastcgi_cache_valid   any      1m;

if( $HTTP_CODE = 200 ) {
  expires 5m;
}
else {
  expires 1m;
}

Is something like the above possible (inside a location container)?

Upvotes: 3

Views: 3475

Answers (1)

cobaco
cobaco

Reputation: 10546

sure, from http://wiki.nginx.org/HttpCoreModule#Variables

$sent_http_HEADER

The value of the HTTP response header HEADER when converted to lowercase and 
with 'dashes' converted to 'underscores', e.g. $sent_http_cache_control, 
$sent_http_content_type...; 

so you could match on $sent_http_response in an if-statement

there's a gotcha though since http://nginx.org/en/docs/http/ngx_http_headers_module.html#expires doesn't list if's as allowed context for the expires directive

you can work around that setting a variable in the if-block, and then referring to it later like so:

set $expires_time 1m;
if ($send_http_response ~* "200") {
  set $expires_time 5m; 
}
expires $expires_time;

Upvotes: 3

Related Questions