如何在nginx conf文件中定义全局变量,如何在http块中定义全局变量,下面的所有服务器和位置都可以使用它。

http{
      some confs
      ...
      //define a global var mabe like
      set APP_ROOT /home/admin
      // and it can be use in all servers and locations below, like
      server {
        root $APP_ROOT/test1
      }

      server {
        root $APP_ROOT/test2
      }
  }

最佳答案

您可以做点小技巧。如果必须从一个server块中的每个http块访问此值,则可以使用map指令。这将如何运作?
map指令允许您在http块中的任何位置使用变量,该变量的值将在某些映射键上计算。讲述的例子:

http {

  ...

  /*
     value for your $my_everywhere_used_variable will be calculated
     each time when you use it and it will be based on the value of $query_string.
  */
  map $query_string $my_everywhere_used_variable {

    /*
       if the actual value of $query_string exactly match this below then
       $my_everywhere_used_variable will have a value of 3
    */
    /x=1&y=2&opr=plus     3;

    /*
       if the actual value of $query_string exactly match this below then
       $my_everywhere_used_variable will have a value of 4
    */
    /x=1&y=4&opr=multi    4;

  /*
    it needs to be said that $my_everywhere_used_variable's value is calculated each
    time you use it. When you use it as pattern in a map directive (here we used the
    $query_string variable) some variable which will occasionally change
    (for example $args) you can get more flexible values based on specific conditions
  */
  }

  // now in server you can use this variable as you want, for example:

  server {

    location / {
      rewrite .* /location_number/$my_everywhere_used_variable;
      /*
         the value to set here as $my_everywhere_used_variable will be
         calculated from the map directive based on $query_string value
      */
    }
  }
}

那么,现在这对您意味着什么?您可以使用map指令通过此简单技巧为所有server块设置全局变量。您可以使用default关键字为 map 值设置默认值。如以下简单示例所示:
map $host $my_variable {
  default lalalala;
}

在此示例中,我们根据$my_variable值计算$host的值,但是实际上$host是什么都没有关系,因为默认情况下我们始终将lalalala设置为变量的值,并且没有其他选项。现在,在代码的所有位置,您将以与所有其他可用变量相同的方式使用$my_variable(例如,使用set指令创建),您将获得lalalala的值

为什么这比仅使用set指令更好呢?正如doc所说,因为set指令只能在server, location and if块内部访问nginx set directive,所以它不能用于为许多server块创建全局变量。

有关map指令的文档可在此处获得:map directive

07-28 01:43
查看更多