Skip to content

Instantly share code, notes, and snippets.

@thomasjsn
Created August 4, 2016 18:35
Show Gist options
  • Save thomasjsn/4050f49a501b8be2d8f3db3a2e7b8b1a to your computer and use it in GitHub Desktop.
Save thomasjsn/4050f49a501b8be2d8f3db3a2e7b8b1a to your computer and use it in GitHub Desktop.
Configuration for microcaching on nginx.
# Setup var defaults
set $no_cache "";
# If non GET/HEAD, don't cache & mark user as uncacheable for X second(s) via cookie
if ($request_method !~ ^(GET|HEAD)$) {
set $no_cache "1";
}
# Drop no cache cookie if need be (for some reason, add_header fails if included in prior if-block)
if ($no_cache = "1") {
add_header Set-Cookie "_mcnc=1; Max-Age=2; Path=/";
add_header X-Microcachable "0";
}
# Dont cache the following URLs
if ($request_uri ~* "/(admin/|ajax/)") {
set $no_cache "1";
}
# Bypass cache if no-cache cookie is set
if ($http_cookie ~* "_mcnc") {
set $no_cache "1";
}
# Bypass cache if flag is set
fastcgi_no_cache $no_cache;
fastcgi_cache_bypass $no_cache;
# Set cache zone
fastcgi_cache microcache;
# Set cache key to include identifying components
fastcgi_cache_key $scheme$host$request_method$request_uri;
# What, and for how long to cache
fastcgi_cache_valid 200 301 1s;
fastcgi_cache_valid 403 404 5m;
# Set files larger than 1M to stream rather than cache
fastcgi_max_temp_file_size 1M;
# Restricts the number of concurrent attempts to populate the cache
fastcgi_cache_lock on;
# Serve from cache if currently refreshing
fastcgi_cache_use_stale updating error timeout invalid_header http_500;
# Send appropriate headers through
fastcgi_pass_header Set-Cookie;
fastcgi_pass_header Cookie;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment