The document describes how to implement an API in Nginx to delete a specific cached file by URI. It explains that Nginx caches files based on an MD5 hash of the request URI. A Lua script is used to take the URI as input, calculate the hashed file path, and delete it using the OS remove command. The script returns a JSON response indicating if the file was successfully deleted. While this approach works, the author later found a simpler existing solution for purging cached items in Nginx using Lua.
2. Who am I?
Yuki Iwamoto
Freelance Engineer
Quitting smoking (40days)
3. Im searching for a Nginx
function
Delete cache function
Only one uri (Not all cache)
4. Example
I want to delete only this uri cache.
http://localhost/entry/11/112233
Sending request like this,
then delete /entry/11/112233 cache
http://localhost:8080/cache_clear_uri/entry/11/112233
5. About nginx cache
File name is md5 hashed from proxy_cache_key
The 鍖rst folder would be the last (n) character
from levels in proxy_cache_path
鍖nd and delete the 鍖le
9. Convert uri to md5
local uri_md5 = ngx.md5( cache_uri )
10. The 鍖rst folder would be the last (1) character (from -1 to -1)
from levels in proxy_cache_path
local 鍖rst_path = string.sub( uri_md5, -1, -1 )
The second folder would be the last (2) character(from -2 to -2)
from levels in proxy_cache_path
local second_path = string.sub( uri_md5, -2,-2 )
The third folder would be the last (3) character (from -3 to -4)
from levels in proxy_cache_path
local third_path = string.sub( uri_md5, -4, -3 )
11. Delete by os.execute ( rm command )
local code = os.execute( "/bin/rm " .. cache_鍖le )
12. Return json (delete or not , and which 鍖le)
ngx.say(cjson.encode({ code = code , cache_鍖le = cache_鍖le }))
ngx.header.content_type = "application/json; charset=utf-8"
{
code:0,
cache_鍖le: /data/nginx/cache/yi/ab/0/1/123ab456cd789ef
}
Json result example
13. I found a better solution
https://scene-si.org/2016/11/02/purging-cached-
items-from-nginx-with-lua/
14. Conclusion
We can do something by Lua
Sometimes, dif鍖cult to 鍖nd a good solution