
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
httpcontext defines the global settings for the NGINX server. In this case, thelistendirective tells NGINX to listen on port 80.The
servercontext defines a virtual host. In this case, thelistendirective tells NGINX to listen on port 8080.The
locationcontext defines a location within a virtual host. In this case, thelistendirective 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.
About the author
I am a DevOps Consultant. 3 years experience with Cloud technologies. 9 years total IT experience in the Linux, Networking and Data Visualization domains. Love listening to music and playing older PC games.
Comments
Join the discussionNo comments yet. Be the first to comment.
Configuring NGINX
In this basic level series, I will post best practices to configure the NGINX web server using Linux based instances.




