ngx.location.capture 只支持相对路径,不能用绝对路径

ngx.location.capture 是非阻塞的,ngx.location.capture也可以用来完成http请求,但是它只能请求到相对于当前nginx服务器的路径,不能使用之前的绝对路径进行访问,但是我们可以配合nginx upstream实现我们想要的功能。

在nginx.cong中的http部分添加如下upstream配置

upstream backend {
    server s.taobao.com;
    keepalive 100;
}
在example.conf配置如下location

     location ~ /proxy/(.*) {
        internal;
        proxy_pass http://backend/$1$is_args$args;
     }

lua 请求可以这么写:

local resp = ngx.location.capture("/proxy/search", {
    method = ngx.HTTP_GET,
    args = {q = "hello"}

})
if not resp then
    ngx.say("request error :", err)
    return
end
ngx.log(ngx.ERR, tostring(resp.status))

--获取状态码
ngx.status = resp.status

--获取响应头
for k, v in pairs(resp.header) do
    if k ~= "Transfer-Encoding" and k ~= "Connection" then
        ngx.header[k] = v
    end
end
--响应体
if resp.body then
    ngx.say(resp.body)
end
原文地址:https://www.cnblogs.com/archoncap/p/5233646.html