Nginx Lua Caching Example
Demonstrates response caching using ngx.shared.DICT with TTL and cache invalidation support.
Components
| File | Purpose |
|---|---|
nginx.conf |
Nginx configuration wiring Lua handlers |
cache_handler.lua |
Shared cache logic with TTL and invalidation |
Features
- Cache responses with configurable TTL
- Manual cache invalidation via purge endpoint
- X-Cache header (HIT/MISS) for debugging
- LRU eviction when memory is full
Usage
-
Define a shared dict in
nginx.conf:lua_shared_dict response_cache 10m; -
Use
cache_handler.luain your location blocks:content_by_lua_file /path/to/cache_handler.lua; -
Purge a specific cache key:
curl -X POST http://example.com/cache/purge -d '{"key": "my_key"}' -
Purge all cached entries:
curl -X POST http://example.com/cache/purge_all