如何在nginx conf文件中定义全局变量

sin*_*ory 27 nginx

如何在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
      }
  }
Run Code Online (Sandbox Code Playgroud)

emk*_*a86 81

你可以做一点小动作.如果必须可以从一个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
      */
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

那么现在,这对你意味着什么?您可以使用该map指令server通过这个简单的技巧为所有块设置全局变量.您可以使用default关键字为地图值设置默认.在这个简单的例子中:

map $host $my_variable {
  default lalalala;
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我们计算了值$my_variable$host值,但实际上它并不重要,$host因为我们总是将lalalala设置为默认情况下的变量值而没有其他选项.现在你的代码中的任何地方都会$my_variable以与所有其他可用变量相同的方式使用(例如使用set指令创建),你将获得lalalala的价值

为什么这比简单地使用set指令更好?因为set指令,如doc说nginx set指令只能在server, location and if块内访问,所以它不能用于为多个server块创建全局变量.

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

  • 为什么这个答案仍未被接受? (18认同)
  • 太好了!我可以使用map指令覆盖全局变量吗? (3认同)
  • 顺便说一句:“set”指令可以在“http.server”内部使用,但不能在“stream.server”内部使用。 (2认同)
  • 仅当使用变量处理 server{} 块内的连接时,这才有效。它不是一个真正的全局变量,因为您无法在服务器配置中的任何地方使用它,例如: ` map $host $host_ip { default 1.2.3.4; } 服务器 { 监听 $host_ip:80; ... }` 这将给出如下错误: nginx: [emerg] host not found in "$host_ip:80" of the "listen" 指令 (2认同)