Project

General

Profile

AbsoLUAtion » redirect-map.lua

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

 
1
-- redirect-map.lua
2
--
3
-- Summary: redirect-map based on url-path
4
--
5
--
6
-- Copyright (c) 2021, Glenn Strauss (gstrauss () gluelogic.com)
7
-- All rights reserved.
8
--
9
-- License: 3-clause BSD
10
--
11
--
12
-- prep:
13
-- * replace all "/path/to" in instructions and script with actual path to files
14
-- * build mcdb
15
--     https://github.com/gstrauss/mcdb/blob/master/README
16
--     https://github.com/gstrauss/mcdb/blob/master/INSTALL
17
-- * install mcdb or use qualified path to mcdbctl when creating database
18
-- * build lua-mcdb and copy mcdb.so to /path/to/
19
--     https://github.com/gstrauss/mcdb/blob/master/contrib/lua-mcdb/README
20
-- * create url-path mapping database (orig-url-path -> new-url-path or URI)
21
--     (see mcdb documentation)
22
-- * modify script below to send one of 301, 302, 303, 307, 308, as desired
23
-- * note: database performs exact matches.  If case-insensitive is required,
24
--     then lowercase input when database is created (lc($_)) and modify code
25
--     below to lowercase request item before querying database
26
--
27
-- lighttpd.conf
28
--   server.modules += ("mod_magnet")
29
--   magnet.attract-raw-url-to = ( "/path/to/redirect-map.lua" )
30

    
31
-- get database file handle (cached in global)
32
-- note: when database changes, 'touch' file containing this script in order to
33
-- trigger lighttpd mod_magnet_cache to reload this script and re-open the mcdb
34
-- (lighttpd etags must be enabled (default) for modified script to be noticed)
35
-- (alternative: skip caching open mcdb in _G to have mcdb opened each request)
36
local redirmap = _G.redirmapdb
37
if (not redirmap) then
38
  -- open database file
39
  local db = "/path/to/redirect-map.mcdb"
40
  local mcdb = package.loaded["mcdb"]
41
  if (not mcdb) then
42
    -- update search path with path to mcdb.so
43
    -- (todo: should skip if already present)
44
    --package.cpath = '/path/to/?.so'
45
    package.cpath = package.cpath .. ';/path/to/?.so'
46
    mcdb = require("mcdb")
47
  end
48
  local redirmapdb, errstr = mcdb.init(db)
49
  if redirmapdb == nil then
50
    io.stderr:write('mcdb.init("' .. db .. '"): ' .. errstr .. '\n')
51
    return 0   -- fail open (not closed); allow request to proceed
52
  end
53
  _G.redirmapdb = redirmapdb
54
  redirmap = redirmapdb
55
end
56

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

    
64
-- allow request to proceed
65
return 0
(5-5/5)