Skip to content

Instantly share code, notes, and snippets.

@LrWm3
Created October 4, 2024 17:31
Show Gist options
  • Save LrWm3/7e4fa936e584b134141127466822113a to your computer and use it in GitHub Desktop.
Save LrWm3/7e4fa936e584b134141127466822113a to your computer and use it in GitHub Desktop.
http {
lua_shared_dict cache_key_store 10m;
server {
location / {
# Read the request body
content_by_lua_block {
ngx.req.read_body()
local body = ngx.req.get_body_data()
# If there's a body, hash it to use as part of the cache key
if body then
local resty_md5 = require "resty.md5"
local md5 = resty_md5:new()
md5:update(body)
local digest = md5:final()
# Store the hash in a variable
ngx.var.cache_key_body_hash = ngx.encode_base64(digest)
else
ngx.var.cache_key_body_hash = "no_body"
end
}
# Use the hashed body as part of the cache key
set $cache_key "$request_method|$scheme://$host$request_uri|$cache_key_body_hash";
proxy_cache_key $cache_key;
# Enable caching for POST requests
proxy_cache_methods GET POST;
# Standard proxy cache settings
proxy_cache my_cache;
proxy_cache_valid 200 10m;
proxy_pass http://backend;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment