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

时间:2020-01-28 13:32:27

标签: nginx lua nginx-location nginx-config openresty

我想定义一个变量,并在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文件的任何部分?

2 个答案:

答案 0 :(得分:0)

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

由于proxy_passcontent_by_lua_block都是内容阶段指令,因此无法在同一位置使用。 content_by_lua_block只是在您的配置中被忽略。

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

答案 1 :(得分:0)

谢谢大家,我将配置文件更改为关注文件,效果很好。

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)。

相关问题