Nginx Lua 代码示例:使用 proxy_pass 转发请求
以下是使用 Lua 代码中使用 Nginx 的 proxy_pass 的示例:
location /api {
default_type 'text/plain';
content_by_lua_block {
ngx.req.set_uri('/api' .. ngx.var.request_uri)
ngx.req.set_header('Host', 'api.example.com')
local res = ngx.location.capture('/proxy');
ngx.say(res.body)
}
}
location /proxy {
internal;
proxy_pass https://api.example.com;
proxy_set_header Host api.example.com;
}
在上述示例中,对于所有以'/api'开头的请求,将请求转发到'https://api.example.com',并将响应返回给客户端。我们使用'ngx.req.set_uri'来设置请求的 URI,并使用'ngx.req.set_header'设置请求头中的'Host'字段。然后,我们使用'ngx.location.capture'来捕获代理请求的响应。最后,我们将响应的主体内容输出到客户端使用'ngx.say'。
原文地址: https://www.cveoy.top/t/topic/nzOZ 著作权归作者所有。请勿转载和采集!