如何在nginx中使用lua编码base64字符串?

我正在nginx中使用lua,以下是编码字符串的代码:

set_by_lua $base64_credential '
              set $es_username os.getenv("ES_USERNAME");
              set $es_pwd os.getenv("ES_PWD");
              return ngx.encode_base64(ngx.var.es_username+":"+ngx.var.es_pwd)
            '

启动服务器后,我得到以下错误:

2021/11/18 01:58:01 [error] 7#7: *151 failed to load inlined Lua code: set_by_lua:2: '=' expected near '$', client: 10.0.6.61, server: localhost, request: "GET /health HTTP/1.1", host: "10.0.1.246:8080"

我使用了这篇文档的语法 https://github.com/openresty/lua-nginx-module#set_by_lua,在设置变量时它没有使用=符号。我做错了什么?

原文链接 https://stackoverflow.com/questions/70013683

点赞
stackoverflow用户7121513
stackoverflow用户7121513

你犯了几个错误。Lua 字符串连接的运算符是 ..。Lua 不希望在运算符之间使用分号。你的 Lua 和 Nginx 配置句法混合了一些奇怪的东西。如果你不需要在其他地方使用 $es_username$es_pwd 变量,那么可以使用:

set_by_lua $base64_credential '
    local es_username = os.getenv("ES_USERNAME")
    local es_pwd = os.getenv("ES_PWD")
    return ngx.encode_base64(es_username .. ":" .. es_pwd)
';

如果你需要在其他地方使用这些变量,那么可以按照你的方式:

set_by_lua $es_username       'return os.getenv("ES_USERNAME")';
set_by_lua $es_pwd            'return os.getenv("ES_PWD")';
set_by_lua $base64_credential 'return ngx.encode_base64(ngx.var.es_username .. ":" .. ngx.var.es_pwd)';
2021-11-18 02:08:32