Skip to content

Instantly share code, notes, and snippets.

@scalp42
Last active December 14, 2015 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scalp42/5137764 to your computer and use it in GitHub Desktop.
Save scalp42/5137764 to your computer and use it in GitHub Desktop.
nginx + lua, stripping the leading / in the $uri
map $uri $uri_stripped {
default null;
~^/(?P<s>.*)$ $s;
}
location / {
set $json $uri_stripped-json; # STILL 200 OK with this line commented out
if ($json ~ "null-json|^-json") { # STILL 200 OK with this line commented out
return 404; } # STILL 200 OK with this line commented out
content_by_lua '
-- ngx.say("Requested: ", ngx.var.json) ## SENDING HEADER BEFORE THE 404 SO ALWAYS 200 OK...
local redis, err = require "resty.redis"
if not redis then
ngx.say("could not load resty redis module")
end
local red = redis:new()
red:set_timeout(500)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local res, err = red:get(ngx.var.json)
if not res then
ngx.say("failed to get key:", err)
return
end
if res == ngx.null then
ngx.status = ngx.HTTP_NOT_FOUD
ngx.say("key not found.") # <- IF THIS LINE COMMENTED OUT = 500 Internal Error
ngx.exit(404)
end
-- ngx.say("result: ", res) # REMOVED FOR SAFETY
local ok, err = red:close()
if not ok then
ngx.say("failed to close: ", err)
return
end
';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment