Directive Inheritance in Nested Location Blocks

2019-02-21 13:16发布

问题:

are the following two nginx server blocks semantically the same, or is there any difference? Does the JSON-specific configuration in the first example inherit the settings of the "/" location? Does it in the second example?

server {
  location / {
     # ...
     location ~* \.json$ {
          # json-specific settings
     }
  }
}

server {
  location / {
     # ...
  }
  location ~*  \.json$ {
    # json-specific settings
  }
}

回答1:

The inheritance of config directives in Nginx is such that directives can only be inherited from contexts higher up the configuration tree and never from contexts on the same level or lower.

So, a location block cannot inherit from another location block but a nested location block can inherit from the parent location block.

I stressed can because there are a number of different types of directives and the inheritance behaviour is a bit different for each.

  1. There are Standard Type Directives which only have one value or set of values attached. These will simply be inherited by contexts lower down the config tree or replaced within that lower context by new values. An example is "index".

  2. Array Type Directives which pass multiple separate values in an array. These will simply be inherited by contexts lower down the config tree or replaced within that lower context by new values. Note that you cannot add to the array. Changing part is replacing it all. An example is "proxy_param". So if you define proxy_param A and proxy_param B at the server level for instance, and then try to define proxy_param C in a location context, "A" and "B" would be wiped out (set to default values). as defining "C" has meant replacing the array.

  3. Command Type Directives such as "try_files" are generally not inherited at all.

So specifically to your question, directives defined in one location block context cannot be inherited by another as in your second example.

Standard and Array type directives defined in the parent location block will be inherited by the nested location block. Command type directives defined in the parent will not be inherited in general.



标签: nginx