Skip to content

Instantly share code, notes, and snippets.

@iwinux
Forked from caquino/backend.conf
Last active October 13, 2015 04:12
Show Gist options
  • Save iwinux/52cd8ab060bd2d2cecc4 to your computer and use it in GitHub Desktop.
Save iwinux/52cd8ab060bd2d2cecc4 to your computer and use it in GitHub Desktop.
invalidate Nginx cache via ngx-lua
server {
listen 80;
server_name backend;
root /usr/share/nginx/www;
index index.html index.html;
location / {
header_filter_by_lua '
ngx.header["X-Expire-Content"] = "/random"
';
content_by_lua '
ngx.say("Adding /random URL to the invalidation queue.")
';
}
location = /random {
content_by_lua '
ngx.say(math.random(100))
';
}
}
lua_shared_dict expire_queue 10m;
proxy_cache_path /dev/shm/nginx/ levels=1:2 keys_zone=default:10m;
server {
listen 80;
root /usr/share/nginx/www;
index index.html index.htm;
server_name frontend;
location / {
header_filter_by_lua '
if ngx.header["X-Expire-Content"] then
ngx.log(ngx.INFO, "Backend sent invalidation header, adding to the queue " .. ngx.header["X-Expire-Content"])
ngx.shared.expire_queue:add(ngx.header["X-Expire-Content"],1)
end
';
set_by_lua $http_cache_purge '
local expire = ngx.shared.expire_queue:get(ngx.var.uri)
if expire then
ngx.log(ngx.INFO, "Removing URL from queue and invalidating, " .. ngx.var.uri)
ngx.shared.expire_queue:delete(ngx.var.uri)
end
return expire
';
add_header X-Cached $upstream_cache_status;
proxy_cache_bypass $http_cache_purge;
proxy_cache default;
proxy_cache_valid 200 302 72h;
proxy_pass http://backend/;
}
}
root@precise32:~# wget -S -q -O - frontend/random # Missed request
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Fri, 29 Nov 2013 05:24:21 GMT
Content-Type: application/octet-stream
Content-Length: 3
Connection: keep-alive
X-Cached: MISS
54
root@precise32:~# wget -S -q -O - frontend/random # Cached request
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Fri, 29 Nov 2013 05:24:23 GMT
Content-Type: application/octet-stream
Content-Length: 3
Connection: keep-alive
X-Cached: HIT
54
root@precise32:~# wget -S -q -O - frontend/ # Invalidation queue access
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Fri, 29 Nov 2013 05:24:27 GMT
Content-Type: application/octet-stream
Content-Length: 44
Connection: keep-alive
X-Expire-Content: /random
X-Cached: MISS
Adding /random URL to the invalidation queue.
root@precise32:~# wget -S -q -O - frontend/random # Cache invalidation request using bypass
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Fri, 29 Nov 2013 05:24:31 GMT
Content-Type: application/octet-stream
Content-Length: 2
Connection: keep-alive
X-Cached: BYPASS
1
root@precise32:~# wget -S -q -O - frontend/random # Cached request
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Fri, 29 Nov 2013 05:24:32 GMT
Content-Type: application/octet-stream
Content-Length: 2
Connection: keep-alive
X-Cached: HIT
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment