如何使用openresty的Lua插件实现uwsgi_pass?

时间:2016-01-18 13:22:59

标签: lua uwsgi openresty

我需要在与特定位置匹配的传入请求上执行一些半复杂逻辑。简而言之,对于符合location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$"的所有网址,需要执行以下操作:

  1. 检查是否存在管理员cookie。如果是这样:
    • 重写网址(/<uuid> - &gt; /mod/<uuid>
    • 执行uwsgi_pass
  2. 否则:
    • 在postgres中为与UUID匹配的条目执行查找
    • 在条目中搜索可用的重定向网址
    • 将客户端重定向到所选的网址
  3. 除了content_by_lua_block位之外,使用uwsgi_pass所有这一切都相当简单;谷歌在这项努力中证明是最无益的......

    如何在uwsgi_pass 中执行content_by_lua_block

1 个答案:

答案 0 :(得分:2)

虽然有点晚,但这是:

location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$" {
          set $uuid $1;                  
          rewrite_by_lua ' 
            local new_url
            if (ngx.var.cookie_admin) then
              new_url = "/modif/" .. ngx.var.uuid                
            else               
              --Get the url from DB using uuid
              local res = ngx.location.capture("/url/" .. ngx.var.uuid);                   
              if (res.status == 200 and res.body)  then 
                new_url = tostring(res.body) --change the uri to the one from DB                  
              else 
                return ngx.exec("@notfound") -- Fallback locaton if no url found in DB
              end               
            end
            ngx.req.set_uri(new_url) -- rewrite uri to new one
          ';
          echo $uri; #test
          #uwsgi_pass upstream_server;
    }

它运行良好,有两个位置用于测试:

location ~ "^/url/(.+)$" {
  internal;      
  set $uuid $1;
  #return 410; # test Uncomment to test @notfound
  echo "/url/from/db/$uuid"; #test   

  #assuming you have postgre module
  #postgres_pass     database;
  #rds_json          on;
  #postgres_query    HEAD GET  "SELECT url FROM your_table WHERE uuid='$uuid'";
  #postgres_rewrite  HEAD GET  no_rows 410;
}

location @notfound {
  echo "Ping!  You got here because you have no cookies!";
}