nginx set variable in location

Solution 1:

Variables can't be declared anywhere nor be used in any directive.

As the documentation of set directive is :

Syntax:   set $variable value;
Default:  —
Context:  server, location, if

The immediate consequence is that you can't use custom variables in an http block.

Update : after a discussion and experiments with AlexeyTen in this chatroom.

  • access_log can contain variables with restrictions. Among them, the lack of buffering and the fact that the leading slash must not be declared in a variable.
  • error_log won't work with variables at all.
  • root directive can contains variables.
  • server_name directive only allows strict $hostname value as a variable-like notation.

Solution 2:

You can use variables declared via map as described in this SO question, which discusses using custom variables in the expression part of location blocks:

https://stackoverflow.com/a/61513351/1604622