Fix redirector
[project/luci.git] / libs / lucid-http / luasrc / lucid / http / handler / catchall.lua
1 --[[
2 LuCId HTTP-Slave
3 (c) 2009 Steven Barth <steven@midlink.org>
4
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 $Id$
12 ]]--
13
14 local srv = require "luci.lucid.http.server"
15 local proto = require "luci.http.protocol"
16 local util = require "luci.util"
17
18 module "luci.lucid.http.handler.catchall"
19
20 Redirect = util.class(srv.Handler)
21
22 function Redirect.__init__(self, name, target)
23 srv.Handler.__init__(self, name)
24 self.target = target
25 end
26
27 function Redirect.handle_GET(self, request)
28 local target = self.target
29 local protocol = request.env.HTTPS and "https://" or "http://"
30 local server = request.env.SERVER_ADDR
31 if server:find(":") then
32 server = "[" .. server .. "]"
33 end
34
35 if self.target:sub(1,1) == ":" then
36 target = protocol .. server .. target
37 end
38
39 local s, e = target:find("%TARGET%", 1, true)
40 if s then
41 local req = protocol .. (request.env.HTTP_HOST or server)
42 .. request.env.REQUEST_URI
43 target = target:sub(1, s-1) .. req .. target:sub(e+1)
44 end
45
46 return 302, { Location = target }
47 end
48
49 Redirect.handle_POST = Redirect.handle_GET
50
51 function Redirect.handle_HEAD(self, request)
52 local stat, head = self:handle_GET(request)
53 return stat, head
54 end