Skip to content

Instantly share code, notes, and snippets.

@markselby
Created October 28, 2013 01:55
Show Gist options
  • Save markselby/7190301 to your computer and use it in GitHub Desktop.
Save markselby/7190301 to your computer and use it in GitHub Desktop.
Nginx LUA script for accessing a Redis request cache
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.log(ngx.ERR, "Redis failed to connect")
return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
end
uri = ngx.var.uri
meta = uri.."-meta"
content = uri.."-content"
-- First get the info hash
local arr, err = red:hgetall(meta)
if not arr then
return ngx.exit(ngx.HTTP_NOT_FOUND) -- NOT FOUND
end
hash = red:array_to_hash(arr)
local ttl, err = red:ttl(content)
if ttl > 0 then
ngx.header.Cache_Control = "max-age="..ttl
end
if hash['etag'] then
if ngx.req.get_headers()["If-None-Match"] == hash['etag'] then
return ngx.exit(ngx.HTTP_NOT_MODIFIED) -- NOT MODIFIED
end
ngx.header.ETag = hash['etag']
end
if hash['content_type'] then
ngx.header.Content_Type = hash['content_type']
end
if hash['content_encoding'] then
ngx.header.Content_Encoding = hash['content_encoding']
end
if hash['content_length'] then
ngx.header.Content_Length = hash['content_length']
end
-- Get the actual content now we know the user needs it
local body, err = red:get(content)
if not body then
return ngx.exit(ngx.HTTP_NOT_FOUND) -- 404 to continue to the upstream
end
if body == ngx.null then
return ngx.exit(ngx.HTTP_NOT_FOUND)
end
ngx.header.Source = "Redis"
ngx.print(body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment