Nginx – Add expires header conditionally based on mime type in nginx

nginx

Running nginx 1.4.1 on ubuntu 12.10

Need to send expires header conditionally and based on mime type/content type of http response.

Added this simple piece of code inside location / {

if ($sent_http_content_type = "text/css") { 
expires 7d;
}

The expires header is not sent even if $sent_http_content_type contains "text/css"

How to fix this ?

Checking file extensions is not enough, because in my app js,css, images are being generated dynamically from php. So need to check the mime and add headers based on that too.

Best Answer

As of nginx 1.7.9:

map $sent_http_content_type $expires {
  default         off;
  application/pdf 42d;
  ~image/         max;
}

expires $expires;

NOTE: $sent_http_content_type is valid, but it cannot be accessed until the server has processed the request...

The answer is pointed at the map entry for application/pdf which allows a date value, or could even be application/pdf modified +42d for example