Search code examples
nginxluanginx-locationnginx-configopenresty

Define and use variable in OpenResty config file


I want to define a variable and use it in the location block in OpenResty config file. Variable is defined same follow:

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;
}

But doesn't pars ngx.var.my_var. How can I define a variable and use it in any part of nginx.conf file?


Solution

  • Thank you all, I changed config file into follow and that works fine.

    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;
    }
    

    Note: in config file for accept @ in a variable should used to percent encoding. So,@ equal to %40 (h@3265 --> h%403265).