Project

General

Profile

AbsoLUAtion » redirect-map.lua

redirect-map based on url-path - gstrauss, 2021-03-18 11:10

 
-- redirect-map.lua
--
-- Summary: redirect-map based on url-path
--
--
-- Copyright (c) 2021, Glenn Strauss (gstrauss () gluelogic.com)
-- All rights reserved.
--
-- License: 3-clause BSD
--
--
-- prep:
-- * replace all "/path/to" in instructions and script with actual path to files
-- * build mcdb
-- https://github.com/gstrauss/mcdb/blob/master/README
-- https://github.com/gstrauss/mcdb/blob/master/INSTALL
-- * install mcdb or use qualified path to mcdbctl when creating database
-- * build lua-mcdb and copy mcdb.so to /path/to/
-- https://github.com/gstrauss/mcdb/blob/master/contrib/lua-mcdb/README
-- * create url-path mapping database (orig-url-path -> new-url-path or URI)
-- (see mcdb documentation)
-- * modify script below to send one of 301, 302, 303, 307, 308, as desired
-- * note: database performs exact matches. If case-insensitive is required,
-- then lowercase input when database is created (lc($_)) and modify code
-- below to lowercase request item before querying database
--
-- lighttpd.conf
-- server.modules += ("mod_magnet")
-- magnet.attract-raw-url-to = ( "/path/to/redirect-map.lua" )

-- get database file handle (cached in global)
-- note: when database changes, 'touch' file containing this script in order to
-- trigger lighttpd mod_magnet_cache to reload this script and re-open the mcdb
-- (lighttpd etags must be enabled (default) for modified script to be noticed)
-- (alternative: skip caching open mcdb in _G to have mcdb opened each request)
local redirmap = _G.redirmapdb
if (not redirmap) then
-- open database file
local db = "/path/to/redirect-map.mcdb"
local mcdb = package.loaded["mcdb"]
if (not mcdb) then
-- update search path with path to mcdb.so
-- (todo: should skip if already present)
--package.cpath = '/path/to/?.so'
package.cpath = package.cpath .. ';/path/to/?.so'
mcdb = require("mcdb")
end
local redirmapdb, errstr = mcdb.init(db)
if redirmapdb == nil then
io.stderr:write('mcdb.init("' .. db .. '"): ' .. errstr .. '\n')
return 0 -- fail open (not closed); allow request to proceed
end
_G.redirmapdb = redirmapdb
redirmap = redirmapdb
end

-- check map for (url-decoded) url-path ("uri.path" in mod_magnet)
local redirect = redirmap(lighty.env["uri.path"]) -- exact match
if (redirect ~= nil) then
lighty.header["Location"] = redirect
return 301 -- HTTP 301 Moved Permanently
end

-- allow request to proceed
return 0
(5-5/6)