Hamid
Hamid

Reputation: 57

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?

Upvotes: 1

Views: 2157

Answers (2)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

If you just need to set a const value to your variable - just use set $my_var 'h@3265'; directive and avoid content_by_lua_block.

It is not possible to use proxy_pass and content_by_lua_block in the same place because both are content phase directives. content_by_lua_block just ignored in your config.

If you need to use more complex Lua logic to set the variable - use set_by_lua_block

Upvotes: 1

Hamid
Hamid

Reputation: 57

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

Upvotes: 0

Related Questions