1 Answer

0 votes
by
Directive and Context

By default, the nginx configuration file can be located in:

/etc/nginx/nginx.conf,  

/usr/local/etc/nginx/nginx.conf, or  

/usr/local/nginx/conf/nginx.conf  

The location of the configuration file will vary depending on the installation procedure of Nginx.

This file has the following content:

Directive

Configuration options in Nginx are known as directives. This option has name and parameters, and this must end with a semicolon (;) otherwise Nginx will fail to load the configuration and produce an error.

Example:

gzip on;  

Context

When we open the core Nginx configuration file in a text editor, the very first thing we will notice that the configurations are organized in a tree-like structure surrounded by curly braces i.e. "{" and "}". These locations surrounded by braces is called context for placing configuration directive. Moreover, the configuration directives along with their parameters, end with a semicolon.

This is the section where we can declare directives. It is similar to the scope in a programming language.

Context can be nested within other contexts, thereby creating a context hierarchy.

Example:

worker_processes 2; # directive in the global context  

http {              # http context  

    gzip on;        # directive in http context  

  

  server {          # server context  

    listen 80;      # directive in server context  

  }  

}  

The lines padded by # are comments and not interpreted by Nginx.

Directive Types

Since the inheritance model differs for different directives, therefore, we have to pay attention when using the same directive in multiple contexts. There is a total of three types of directives, each with its inheritance model.

Normal

It has one value per context. And we can define it only once in the context. Subcontexts can override the parent directive, but this override will be valid only in a given subcontext.

gzip on;  

gzip off; # illegal to have two normal directives in the same context   

  

server {  

  location /downloads {  

    gzip off;  

  }  

  

  location /assets {  

    # gzip is in here  

  }  

}  

Array

Adding too many directives in the same context will add to the values instead of overwriting them altogether. Defining a directive in a subcontext will override all the values of a parent in the given subcontext.

error_log /var/log/nginx/error.log;  

error_log /var/log/nginx/error_notive.log notice;  

error_log /var/log/nginx/error_debug.log debug;  

  

server {  

  location /downloads {  

    # this will override all the parent directives  

    error_log /var/log/nginx/error_downloads.log;  

  }  

}  

Action Directive

Actions are directives that are used to change things. Their behavior of inheritance will depend on the module.

For example: In the rewrite directive case, every matching directive will be executed.

server {  

  rewrite ^ /foobar;  

  

  location /foobar {  

    rewrite ^ /foo;  

    rewrite ^ /bar;  

  }  

}  

If we try to fetch /sample:

A server rewrite is executed, rewriting is done from /sample to /foobar.

Then the location /foobar is matched.

The 1st location rewrite is executed, rewriting from /foobar, to /foo.

The 2nd location rewrite is executed, rewriting from /foo, to /bar.

Let's see a different behavior then what the return directive provides:

server {  

  location / {  

    return 200;  

    return 404;  

  }  

}
by
From the above case, the 200 status is returned immediately.

Type of Context

Let's see an example.

# Global context  

 ...  

 ...  

 # http context  

http{  

     ...  

     ...  

     # Server context  

     server {  

              listen 80;  

              server_name example.com;  

              ...  

              ...  

              # Location context  

              location / {              

                          root /var/www/html;              

                          try_files $uri $uri/ =404;          

                          ...  

                          ...  

             }  

    }  

    # Server context  

    server {  

             ...  

             ...  

             # Location context  

             location / {   

                         ...  

                         ...  

             }  

    }  

    ...  

    ...  

}  

From the above example, we can see that the HTTP context declares settings for HTTP protocol. Virtual host settings are declared in the server context and also contained in the http context. Locations contexts that are used to store URLs settings are contained within a server context.

Main Context

The most general context is the main context. It is also called the global context. The main context sets the settings for Nginx globally, and is the only context that is not contained within the typical context blocks and that is not surrounded by curly braces.

The main context is placed at the beginning of the core Nginx configuration file. The directives for this context cannot be inherited in any other context and therefore can't be overridden.

The main context is used to configure details that affect the entire application on a basic level. Some common details that are configured in the main context are the user and group to run the worker processes as, the total number of workers, and the file to save the main process ID. The default error file for the entire application can be set at the main context level.

user nginx;  

worker_processes auto;  

pid /run/nginx.pid;  

...  

...  

Events Context

The events context sets global options for connection processing. The events context is contained within the main context. There can be only one event context defined within Nginx configuration.

Nginx uses an event-based connection processing model, so the directive defined within this context determines how worker processes should handle connections.

# main context  

events {  

        # events context  

        worker_connections 768;   

        multi_accept on;  

}  

...  

...  

HTTP Context

The HTTP context is used to hold the directives for handling HTTP or HTTPS traffic.

The HTTP context is a sibling of the context of the event, so they must be listed side-by-side, rather than nested. They both are the child of the main context.

Lower contexts handle the request, and the directives at this level control the defined defaults for every virtual server.

user nginx;  

worker_processes auto;  

pid /run/nginx.pid;  

...  

...  

events {  

        # events context  

        worker_connections 768;   

        multi_accept on;  

        ...  

        ...  

}  

http {  

       sendfile on;   

       tcp_nopush on;     

       tcp_nodelay on;    

       keepalive_timeout 65;  

       ...  

       ...  

}  

Server Context

The server context is declared within the http context. The server context is used to define the Nginx virtual host settings. There can be multiple server contexts inside the HTTP context. The directives inside the server context handle the processing of requests for resources associated with a particular domain or IP address.

The directives in this context can override many of the directives that may be defined in the http context, including the document root, logging, compression, etc. In addition to the directives that are taken from the http context, we can also configure files to try to respond to requests, issue redirects, and rewrites, and set arbitrary variables.

user nginx;  

worker_processes auto;  

pid /run/nginx.pid;  

...  

...  

events {  

         # events context  

         worker_connections 768;      

         multi_accept on;  

         ...  

         ...  

 }  

http {  

       sendfile on;   

       tcp_nopush on;     

       tcp_nodelay on;    

       keepalive_timeout 65;  

       ...  

       ...  

  

       server {  

                listen 80;  

                server_name domain1.com;  

                root /var/www/html/wordpress;  

                ...  

       

       }  

       server {  

                listen 80;  

                server_name domain2.com;  

                root /var/www/html/drupal;  

                ...  

       

       }  

}  

Location Context

Location contexts define directives to handle the request of the client. When any request for resource arrives at Nginx, it will try to match the URI (Uniform Resource Identifier) to one of the locations and handle it accordingly.

Multiple location contexts can be defined within the server blocks. Moreover, a location context can also be nested inside another location context.

http {  

       ...  

       ...  

  

       server {  

                listen 80;  

                server_name domain1.com;  

                root /var/www/html/wordpress;  

                ...  

                location /some_url {    

                # configuration for processing URIs starting with /some_url  

                }  

                location /another_url {    

                # configuration for processing URIs starting with /another_url  

                }      

       }  

       server {  

                listen 80;  

                server_name domain2.com;  

                root /var/www/html/drupal;  

                ...  

                location /some_url {    

                # configuration for processing URIs starting with /some_url    

                }  

                location /some_other_url {    

                # configuration for processing URIs starting with /some_other_url  

                }    

       

       }  

}  

Upstream Context

The upstream context is used to configure and define an upstream server. This context is allowed to define a pool of backend servers that Nginx can proxy the used when request. This context is usually we are configuring proxies of various types.

Upstream context enables Nginx to perform load balancing while proxying the request. This context is defined inside the HTTP context and outside any server context.

The upstream context is referenced by name within server or location blocks. And then pass the requests of a certain type to the pool of defined servers. The upstream will then use an algorithm (by default round-robin) to determine which specific server need to be used to handle the request.

http{  

     ...  

     ...  

     upstream backend_servers {  

                                server host1.example.com;  

                                server host2.example.com;  

                                server host3.example.com;  

     }  

  

server {  

             listen 80;  

             server_name example.com;  

             location / {  

                           proxy_pass http://backend_servers;  

             }  

  }  

}  

Mail Context

Although Nginx is most often used as a web or reverse proxy server, it can also be used as a high-performance mail proxy server. The context that is used for this type of directives is called the mail context. The mail context is defined inside the main or global context or outside of the http context.

The main purpose of the mail context is to provide an area for configuring a mail proxying solution on the server. Nginx can redirect authentication requests to an external authentication server. It can then provide access to POP3, SMTP, and IMAP mail servers for serving the actual mail data.

In general, a mail context will look like this:

# main context  

mail {  

       server_name mail.example.com;  

       auth_http   localhost:9000/cgi-bin/nginxauth.cgi;  

       proxy_pass_error_message on;  

       ...  

}  

http {  

  

}  

...  

...  

If context

The if context is used to allow conditional execution of directives defined within it. If the context is just like "if statement" of any other programming languages. The if context will execute the contained instructions if a given condition returns true.

The if context should be avoided as far as possible due to some limitations of it. Use this link to know more about why nginx should be avoided, which is discussed here.

http {  

        server {  

                     location /some_url {  

                     if (test_condition) {  

                          # do some stuff here  

                   }  

  

         }  

    }  

}  

Limit_except context

The limit_except context is used to prevent the use of all HTTP methods within the location context except the ones that we explicitly allow. For example, if certain clients should have access to POST content and everyone should have the ability to read the content, then we can use limit_except context for this.

...  

...  

location /wp-admin/ {   

    limit_except GET {   

      allow 127.0.0.1;   

      deny all;   

    }   

}  

...  

...  

The above example allows all the visitors to use the GET header in the location /wp-admin. The other HTTP headers are permitted if it is originated from local addresses only.

Miscellaneous Contexts

Apart from the above contexts, there are few other contexts available in Nginx and are described below. These contexts are dependent on optional modules and are used very rarely.

split_clients: The split_client context splits the client's request into two or more categories. This context is defined in the HTTP context and is mainly used for A/B testing.

geo: The geo context categorizes client IP addresses. It is used to map the value of a variable depending on the connecting IP addresses.

charset_map: This context is used to add specific charset to the "Content-Type" response header field. Also, using the context, one can convert data from one charset to another charset with some limitations.

map: The map context is used to create variables whose values depend on the values of other variables and are defined in the http context.

perl/perl_set: It is used to implement location and variable handlers in Perl and insert Perl calls into SSI. Further, with the help of the perl_set context, we can install a Perl handler for a specific variable.

types: The types context maps the MIME types with correct file extensions. This context may appear in the http context, server context or location context.

Related questions

0 votes
asked Sep 5, 2019 in NGINX by Robin
0 votes
asked Sep 5, 2019 in NGINX by Robin
...