How to define a global variable in nginx conf file, define a global var in http block,and all servers and locations below can use it.
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
}
}
You can do a little trick. If this value must be accessible from every
server
block in onehttp
block you can usemap
directive. How will this work?The
map
directive allows you to use a variable anywhere in anhttp
block which value will be calculated on some map key. All-telling example:So now, what does this mean for you? You can use the
map
directive to set a global variable for allserver
blocks with this simple trick. You can use thedefault
keyword to set a default value for your map value. As in this simple example:In this example we calculate the value of
$my_variable
on the$host
value, but in fact it doesn't matter what$host
is because we will always set lalalala as the value for our variable by default and without other options. Now everywhere in your code when you will use$my_variable
in the same way as all other available variables (for example created withset
directive) you will get value of lalalalaAnd why is this better than simply using the
set
directive? Because theset
directive, as doc says nginx set directive is only accessible insideserver, location and if
blocks, so it cannot be used to create global variable for a number ofserver
blocks.Docs about
map
directive are available here: map directive