job.answiz.com
  • 4
Votes
name
name Punditsdkoslkdosdkoskdo

Setting lapse headers for static content served from nginx

I'm using nginx to server my static content, is there a way that I can set the expires headers for every file that meets a specific rule? For example can I set the expires header for all files that have an extension of '.css'?

All the aforementioned solutions will deny the possibility to have different aliases for different paths. Also for the sake of having all your different cache expirations in one place you should use nginx map in the following way.

...

# Expires mappings
map $sent_http_content_type $expires {
    default                    off;
    text/html                  epoch;
    text/css                   max;
    application/javascript     7d;
    ~image/                    max;
}

...

server {
   listen ...;

   expires $expires;
   location /assets/ {
      # It is now possible to serve some resources from different path
      alias /var/www/my_other_path/
   }

   # and have them all have same expirations
   location / {
       try_files $uri $uri/ /index.html;
   }
...
}

Off disables caching, epoch (for unix epoch) results in resource always being refetched, max sets the date to browser max value.

The ~image/ matches any image types.

  • 1
Reply Report

You can also set the expires to maximum. Here is the directive I use for css and js.

# Set css and js to expire in a very long time
location ~* ^.+.(css|js)$ {
    access_log off;
    expires max;
}
  • 1
Reply Report

I prefer to do a more complete cache header, in addition to some more file extensions. The '?' prefix is a 'non-capturing' mark, nginx won't create a $1. It helps to reduce unnecessary load.

location ~* .(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}
  • 1
Reply Report