1

我想请求一些 api 并将响应设置为 nginx 变量。但它说"set_by_lua_block" directive is not allowed here。我怎样才能做到这一点?

http {
  set_by_lua_block $hostIp {
    local http = require 'resty.http'
    local httpc = http.new()
    local res, err = httpc:request_uri('http://some-pai')
    local body, err = res:read_body()
    ngx.log(ngx.INFO, "Using ngx.INFO")
    ngx.log(ngx.INFO, body)
    return body
  }

  ...
}
4

1 回答 1

1

在 http 上下文中不允许 set_by_lua_block

https://github.com/openresty/lua-nginx-module#set_by_lua

set_by_lua_* 可以在服务器上下文中使用。

但是你的代码无论如何都不会工作,因为 resty.http 使用 cosocket API。

在 set_by_lua 的上下文中,至少以下 API 函数当前被禁用:

输出 API 函数(例如,ngx.say 和 ngx.send_headers)

控制 API 函数(例如,ngx.exit)

子请求 API 函数(例如,ngx.location.capture 和 ngx.location.capture_multi)

Cosocket API 函数(例如,ngx.socket.tcp 和 ngx.req.socket)。

睡眠 API 函数 ngx.sleep。

如果您真的需要在 nginx 启动之前请求一次 - 编写脚本并设置环境变量。然后

set_by_lua $my_var 'return os.getenv("MY_VAR")';
于 2016-12-13T20:45:00.867 回答