如何在openresty的Lua插件中使用uwsgi_pass?

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

  1. 检查是否存在管理 cookie。如果有:

    • 重写 URL(/<uuid> -> /mod/<uuid>)
    • 执行 uwsgi_pass
  2. 否则:

    • 在 postgres 中执行查找,查找 UUID 匹配的条目
    • 在条目中搜索可用的重定向 URL
    • 将客户端重定向到所选 URL

所有这些都使用 content_by_lua_block 非常简单,除了 uwsgi_pass 部分;在这方面,谷歌并没有提供太多帮助……

如何在 content_by_lua_block 中执行 uwsgi_pass

点赞
用户1058509
用户1058509

虽然有点晚了,但这是:

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
              --使用uuid从DB获取url
              local res = ngx.location.capture("/url/" .. ngx.var.uuid);
              if (res.status == 200 and res.body)  then
                new_url = tostring(res.body) --将uri更改为从DB中获取到的uri
              else
                return ngx.exec("@notfound") --如果在DB中找不到url,则回退到其他位置
              end
            end
            ngx.req.set_uri(new_url) --将uri重写为新的uri
          ';
          echo $uri; #测试
          #uwsgi_pass upstream_server;
    }

它能够很好地工作,可以用以下两个位置进行测试:

location ~ "^/url/(.+)$" {
  internal;
  set $uuid $1;
  #return 410; #测试 取消注释以测试@notfound
  echo "/url/from/db/$uuid"; #测试

  #假设您有postgre模块
  #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!";
}
2016-02-14 00:07:08