在 OpenResty 配置文件中定义和使用变量

Define and use variable in OpenResty config file

我想定义一个变量并在 OpenResty 配置文件的位置块中使用它。 变量定义相同:

location /projects {
   set $my_var '';
   content_by_lua_block {
      ngx.var.my_var = "h@3265";
   }

   header_filter_by_lua '
      local val = ngx.header["x-ausername"]
      if val then
         if (val ~= "sample3")
         and (val ~= ngx.var.my_var) -- this variable does not work
         and (val ~= "sample2")
         and (val ~= "sample1")
         and (val ~= "anonymous") then
            return ngx.exit(400)
         end
      end
   ';

   proxy_pass        http://MYSERVER.LOCAL:6565;
   proxy_set_header Host $host:$server_port;
   access_log off;
}

但不符合 ngx.var.my_var。 如何定义一个变量并在 nginx.conf 文件的任何部分使用它?

如果您只需要为您的变量设置一个常量值 - 只需使用 set $my_var 'h@3265'; 指令并避免 content_by_lua_block.

不可能在同一个地方使用 proxy_passcontent_by_lua_block,因为它们都是内容阶段指令。 content_by_lua_block 只是在您的配置中被忽略了。

如果您需要使用更复杂的 Lua 逻辑来设置变量 - 使用 set_by_lua_block

谢谢大家,我将配置文件更改为follow并且工作正常。

location /projects {

   header_filter_by_lua '
      local my_var = "h%403265"             #**Note**
      local val = ngx.header["x-ausername"]
      if val then
         if (val ~= "sample3")
         and (val ~= my_var) 
         and (val ~= "sample2")
         and (val ~= "sample1")
         and (val ~= "anonymous") then
            return ngx.exit(400)
         end
      end
   ';

   proxy_pass        http://MYSERVER.LOCAL:6565;
   proxy_set_header Host $host:$server_port;
   access_log off;
}

注意:在配置文件中接受@变量应该使用百分比编码。所以,@ 等于 %40 (h@3265 --> h%403265).