Directive inheritance in NGINX

Directive inheritance in NGINX is a way of reusing configuration directives in different parts of the NGINX configuration file. Directives are inherited from the parent context to the child context. A context is a block of configuration directives. The main contexts in NGINX are:

  • Global context: This is the top-level context and applies to the entire NGINX configuration.

  • HTTP context: This context applies to the HTTP protocol.

  • Server context: This context applies to a specific server block.

  • Location context: This context applies to a specific location within a server block.

For example, the following configuration defines a global directive worker_processes and a server directive listen. The worker_processes directive is inherited by the server context and the listen directive is inherited by the location context.

worker_processes 2;

http {
  server {
    listen 80;

    location / {
    }
  }
}

In this configuration, NGINX will create two worker processes and listen on port 80. The location context will inherit the worker_processes directive from the http context and the listen directive from the server context.

There are a few things to keep in mind about directive inheritance in NGINX:

  • Directives can only be inherited from a parent context to a child context.

  • Directives cannot be inherited from a child context to a parent context.

  • Directives can be overridden in a child context.

For example, the following configuration defines a server directive listen in the http context and a location directive listen in the location context. The listen directive in the location context will override the listen directive in the http context.

http {
  listen 80;

  server {
    listen 8080;

    location / {
      listen 80;
    }
  }
}

Here is a breakdown of the configuration:

  • The http context defines the global settings for the NGINX server. In this case, the listen directive tells NGINX to listen on port 80.

  • The server context defines a virtual host. In this case, the listen directive tells NGINX to listen on port 8080.

  • The location context defines a location within a virtual host. In this case, the listen directive tells NGINX to listen on port 80 for requests to the / location.

Therefore, NGINX will listen on port 8080 for all requests, except for requests to the / location, which will be listened to on port 80.

I hope this explanation of directive inheritance in NGINX is helpful. Please let me know in the comments if you have any other questions.