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

相关文章

文章浏览阅读3.7k次,点赞2次,收藏5次。Nginx学习笔记一、N...
文章浏览阅读1.7w次,点赞14次,收藏61次。我们在使用容器的...
文章浏览阅读1.4k次。当用户在访问网站的过程中遇到404错误时...
文章浏览阅读2.7k次。docker 和 docker-compose 部署 nginx+...
文章浏览阅读1.3k次。5:再次启动nginx,可以正常启动,可以...
文章浏览阅读3.1w次,点赞105次,收藏182次。高性能:Nginx ...