url rewrite功能实现

背景: abc.com/live/stream.m3u8 需要改写成abc.com/live/stream/index.m3u8
通过lua实现的逻辑如下

  1. 修改nginx.conf 主配置文件,增加rewrite_by_lua_file ,指定改写脚本
http {
	rewrite_by_lua_file lua/rewrite/rewrite_main.lua;
}
  1. lua/rewrite/rewrite_main.lua 文件编写处理逻辑
local function split(str,delimiter)
    local dLen = string.len(delimiter)
    local newDeli = ''
    for i=1,dLen,1 do
        newDeli = newDeli .. "["..string.sub(delimiter,i,i).."]"
    end

    local locaStart,locaEnd = string.find(str,newDeli)
    local arr = {}
    local n = 1
    while locaStart ~= nil
    do
        if locaStart>0 then
            arr[n] = string.sub(str,1,locaStart-1)
            n = n + 1
        end

        str = string.sub(str,locaEnd+1,string.len(str))
        locaStart,locaEnd = string.find(str,newDeli)
    end
    if str ~= nil then
        arr[n] = str
    end
    return arr
end


local function m3u8_rewrite()
   local uri = ngx.var.uri
   ngx.log(ngx.ERR, "uri: ".. uri)
    --获取最后一段
    local uri_list = split(uri,"/")
    if uri_list[4] then
        return uri
    end
    local app = uri_list[2]
    ngx.log(ngx.ERR, "app: "..app )
    local name = split(uri_list[3], ".")[1]
    ngx.log(ngx.ERR, "starturi: "..app .."; name: ".. name)
    return string.format("/%s/%s/index.m3u8", app,name)
end

local function process()
    local rewrite_uri = m3u8_rewrite()
    ngx.log(ngx.INFO, "rewrite_uri: ".. rewrite_uri)
    ngx.req.set_uri(rewrite_uri)
end

process()
posted @ 2023-04-05 20:03  better_feng  阅读(39)  评论(0编辑  收藏  举报