在定时器中不能使用ngx.location.capture方法,否则会报错API disabled in the context of ngx.timer,可以借用resty.http实现
1 直接使用方式
该方式使用httpc的接口实现如下
local http = require "resty.http"
-- 创建 HTTP 客户端
local httpc = http.new()
-- 指定 Unix Domain Socket 地址 (格式: unix:/path/to/socket.sock)
local socket_path = "unix:/tmp/your_backend.sock"
-- 连接到 socket (端口必须设为 0)
local ok, err = httpc:connect(socket_path, 0)
if not ok then
ngx.log(ngx.ERR, "连接失败: ", err)
return
end
-- 发送请求 (必须设置 Host 头!)
local res, err = httpc:request({
method = "GET",
path = "/api/endpoint", -- 请求路径
headers = {
["Host"] = "unix_domain_backend", -- 关键:任意有效 Host 值
["Connection"] = "close" -- 请求后关闭连接
}
})
-- 处理错误
if not res then
ngx.log(ngx.ERR, "请求失败: ", err)
httpc:close()
return
end
-- 读取响应体
local body = res:read_body()
-- 关闭连接
httpc:close()
-- 输出结果
ngx.say("状态码: ", res.status)
ngx.say("响应体: ", body)
2 间接使用方式
该方式使用request_uri替代上面的connect,request和read_body,一步即可完成,但需要一个location转发到nuix socket
local hc = httpc.new()
local url = "h.ttp://127.0.0.1/proxy_unix_domain/api/endpoint?unixaddr=your_backend.sock&arg=arg"
local res, err = hc:request_uri(url)
if not res then
ngx.log(ngx.ERR, "请求失败: ", err)
else
-- 读取响应体
local body = res.body
end
-- 关闭连接
httpc:close()
对应的location如下:
location ~ ^/proxy_unix_domain/(.*) {
proxy_set_header Host $host;
set $ori_uri $1;
rewrite_by_lua_block {
local uri = "/"..ngx.var.ori_uri
ngx.req.set_uri(uri)
}
proxy_pass h.ttp://unix:/tmp/$arg_unixaddr;
}
该location的代理地址通过参数来传递:unix:/tmp/your_backend.sock
请求uri通过改写方式从原始请求截取