Nginx caching

From KOP KB
Jump to: navigation, search

This can be used to control how long certain files be cached or whether to cache them at all. You can change the expire values and add certain values yourself. Due to the nature of how php is introduced to nginx you will need to set the expires function within the php block in your vhost server block. My preference was to put this into a separate file and then include it where needed but most of the time you can put the include statement somewhere within the main nginx.conf.

# Expire rules for static content

# cache.appcache, your document html and data
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
  expires -1;
  # access_log logs/static.log; # I don't usually include a static log
}

# Feed
location ~* \.(?:rss|atom)$ {
  expires 1h;
  add_header Cache-Control "public";
}

# Media: images, icons, video, audio, HTC
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
  expires 1M;
  access_log off;
  add_header Cache-Control "public";
}

# CSS and Javascript
location ~* \.(?:css|js)$ {
  expires 1y;
  access_log off;
  add_header Cache-Control "public";
}

SOURCE: https://serversforhackers.com/c/nginx-caching