function string.split(str)
  local splitlist = {};
  string.gsub(str, '[^,]+', function(w) table.insert(splitlist, w) end )
  return splitlist;
end

function isInTable(value, tbl)
  for k,v in ipairs(tbl) do
    if v == value then
    return true;
    end
  end
  return false;
end

local path = ngx.var.normalPath;
local channelPath = ngx.var.channelPath;

-- 没有设置渠道,返回旧目录
if (ngx.var.registerChannel == '' and ngx.var.merchantChannel == '') then
  return path;
end

-- 解析渠道设置
local register = string.split(ngx.var.registerChannel);
local merchant = string.split(ngx.var.merchantChannel);

-- cookie值
local register_cookie = ngx.var.cookie_registerFrom
local merchant_cookie = ngx.var.cookie_merchantId

-- uri参数值
local args = ngx.req.get_uri_args()
local register_uri = args['registerFrom']
local merchant_uri = args['merchantId']

-- 优先匹配参数中的registerFrom
if (register_uri) then
  hitRegister = isInTable(register_uri, register)
else
  hitRegister = isInTable(register_cookie, register)
end

-- 优先匹配参数中的merchantId
if (merchant_uri) then
  hitMerchantId = isInTable(merchant_uri, register)
else
  hitMerchantId = isInTable(merchant_cookie, register)
end

local baiTiao = '222';

-- 
if (register_uri) then
  isBaitiao = register_uri == baiTiao
else
  isBatitiao = register_cookie == baiTiao
end

-- 是白条，未设置merchantId规则，命中
if (isBaitiao and ngx.var.merchantChannel == '') then
  return channelPath
end

-- 是白条，设置了merchantId规则，匹配merchantId后命中
if (isBaitiao and ngx.var.merchantChannel ~= '' and hitMerchantId) then
  return channelPath
end

-- 不是白条，匹配registerFrom后命中
if ( not isBaitiao and hitRegister) then
  return channelPath
end

return path;
