Hello,
I would like to create dynamic routing based based on request_uri patterns.
I would like to redirect
http://mydomain.com/user1/app1/subfolders to
https://mydomain.com/?server=$target/user1/app1 if /user1/app1 (first two folders) has a redis key.
# redis-cli
127.0.0.1:6379> set /user/app1
server1.comOK
In this case the url rewrite will be
https://mydomain.com/?server=server1.com/user1/app1If there is no value for /user/app1 key, It will be redirect to another predefined server .
my below code is based on redis sample openresty webpage.
location / {
resolver 8.8.4.4; # use Google's open DNS server
set $target '';
access_by_lua_block {
function split(pString, pPattern)
local Table = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pPattern
local last_end = 1
local s, e, cap = pString:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(Table,cap)
end
last_end = e+1
s, e, cap = pString:find(fpat, last_end)
end
if last_end <= #pString then
cap = pString:sub(last_end)
table.insert(Table, cap)
end
return Table
end
local myuri = ngx.var.request_uri
list=split(myuri,"/")
userapp="/" .. list[1] .. "/" .. list[2]
if not userapp then
ngx.log(ngx.ERR, "no userapp path found")
return ngx.exit(400)
end
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 second
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.log(ngx.ERR, "failed to connect to redis: ", err)
return ngx.exit(500)
end
local host, err = red:get(userapp)
if not host then
ngx.log(ngx.ERR, "failed to get redis key: ", err)
return ngx.exit(500)
end
if host == ngx.null then
ngx.log(ngx.ERR, "no aga host found for key ", key)
return ngx.exit(400)
end
ngx.var.target = host
}
rewrite ^/(.*)
https://mydomain.com/?server=$target/$1 permanent;
The problem is here that rewrite line is processed first and I can't do anything on lua block.
How can I use above rewrite line in my lua block.
Or do you have any other suggestion?
btw I could not find a native comand to parse uri / pattern. then I used a lua script to do this.