Skip to content

Instantly share code, notes, and snippets.

@theothertom
Created October 17, 2017 14:26
Show Gist options
  • Save theothertom/62aab38ddc2a4900d52e8bd119e078e5 to your computer and use it in GitHub Desktop.
Save theothertom/62aab38ddc2a4900d52e8bd119e078e5 to your computer and use it in GitHub Desktop.
Nginx Lua generic redirect caching
#user nobody;
worker_processes auto;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
lua_shared_dict redirects 50m;
server {
listen 80;
server_name localhost;
location / {
access_by_lua_block {
local redir = ngx.shared.redirects
local args = ngx.var.args
-- section/id/slug
-- section/subsection/id/slug
m, err = ngx.re.match(ngx.var.uri, "(.*/)+([0-9]*)/.+")
if err then
ngx.log(ngx.ERR, "error: ", err)
return
end
if not m then
return
end
if redir:get(m[2]) then
-- We have cached state about this article ID
if redir:get(m[2]) == ngx.var.uri then
-- URL is already canonical
return
else
-- URL not canonical, redirect user
if args then
return ngx.redirect(redir:get(m[2]) .. "?" .. args)
else
return ngx.redirect(redir:get(m[2]))
end
end
else
-- We don't know about this URL, find out!
ngx.req.read_body()
res = ngx.location.capture(ngx.var.uri)
if res.status == 301 then
redir:set(m[2], res.header['Location'])
ngx.redirect(res.header['Location'])
else
redir:set(m[2], ngx.var.uri)
end
end
}
#Not redirecting, proxy
proxy_pass http://backend;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment