如何使用 openresty 的 Lua 插件实现 uwsgi_pass?
How can I achieve a uwsgi_pass with openresty's Lua plugin?
我需要对与特定位置匹配的传入请求执行一些半复杂的逻辑。简而言之,对于所有符合 location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$"
的 url,需要进行以下操作:
- 检查是否存在管理 cookie。如果是这样:
- 重写 URL (
/<uuid>
-> /mod/<uuid>
)
- 执行
uwsgi_pass
- 其他:
- 在 postgres 中查找匹配 UUID 的条目
- 在条目中搜索可用的重定向 URL
- 将客户端重定向到选定的 URL
除了 uwsgi_pass
位外,使用 content_by_lua_block
所有这些都相当简单; Google 已证明在这项努力中最无益...
如何在 content_by_lua_block
中执行 uwsgi_pass
?
虽然晚了点,但还是:
location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$" {
set $uuid ;
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 ;
#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!";
}
我需要对与特定位置匹配的传入请求执行一些半复杂的逻辑。简而言之,对于所有符合 location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$"
的 url,需要进行以下操作:
- 检查是否存在管理 cookie。如果是这样:
- 重写 URL (
/<uuid>
->/mod/<uuid>
) - 执行
uwsgi_pass
- 重写 URL (
- 其他:
- 在 postgres 中查找匹配 UUID 的条目
- 在条目中搜索可用的重定向 URL
- 将客户端重定向到选定的 URL
除了 uwsgi_pass
位外,使用 content_by_lua_block
所有这些都相当简单; Google 已证明在这项努力中最无益...
如何在 content_by_lua_block
中执行 uwsgi_pass
?
虽然晚了点,但还是:
location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$" {
set $uuid ;
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 ;
#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!";
}