Understanding NGINX Configuration File

Filed Under: NGINX

It’s very important to understand the structure of the NGINX configuration file to get the best performance from your server. Further, by applying directives on right context in a NGINX configuration will enable you to eliminate repetitive codes and manage your infrastructure better.

Therefore to help you understand the structure of the NGINX configuration file, this article will focus on describing the structure of the NGINX configuration file in details.

What is Nginx Context?

Let us start with checking the location of the NGINX configuration file. The core configuration file (nginx.conf) can be found in /etc/nginx. The location will vary depending on the installation procedure of NGINX.

Open the core NGINX configuration file in a text editor. The very first thing that you will notice that the configurations are organized in a tree-like structure surrounded by curly braces { and }. These locations surrounded by braces is known as Context for placing configuration directive. Moreover, the configuration directives along with their parameters end with a semicolon.

In NGINX, contexts can be nested within other contexts thereby creating a hierarchy. In the following example, the HTTP context declares settings for HTTP protocol. Virtual host settings are declared in the server context and are contained in the http context. Locations contexts that are used to store settings for URLs are contained within a server context.



# 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 / { 
                         ...
                         ...
             }
    }
    ...
    ...
}

NGINX Config File – Main context

The main context is used to set the settings for NGINX globally and is the only context that is not surrounded by curly braces. Generally, The main context is placed at the beginning of the core NGINX configuration file. The directives for the main context cannot be inherited in any other context and therefore cannot be overridden.


user nginx;
worker_processes auto;
pid /run/nginx.pid;
...
...

NGINX Config File – Events context

The events context is used to set global options for connection processing. The events context is included in the main context and there can be only one such context. The directives that you can place in this context are setting connection processing methods, the number of connections along with a few other directives.


# main context

events {
        # events context
      	worker_connections 768;	
      	multi_accept on;
}
...
...

NGINX Config File – HTTP context

The HTTP context holds directives for handling HTTP and HTTPS traffic. The HTTP context is the child of the main context and is absolutely needed in every server context where virtual hosts settings are declared for your domains.


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;
       ...
       ...
}

NGINX Config File – Server context

The NGINX virtual host settings are defined in the server contexts which in turn are contained in the HTTP context. There can be multiple server contexts inside the HTTP context. The directives inside server context govern the processing of requests for resources associated with a particular domain or IP address.


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;
                ...
     
       }
}

NGINX Config File – Location context

Location contexts are used to define directives to handle client request. When a request for resource arrives at NGINX, it will try to match the URI to one of the locations and handle it accordingly.

Multiple Location contexts can be defined inside 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 allowed to define a pool of back-end servers that NGINX can proxy the request. The context enables NGINX to perform load balancing while proxying the request. The upstream context is defined inside the HTTP context and outside any server context.

Once upstream servers have been defined, the name of the same is available within the server context to pass the request to the pool of back-end servers.


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

NGINX can proxy the IMAP, POP3, and SMTP protocols to one of the upstream mail servers or to an external mail service where the mail accounts are hosted. To accomplish it, NGINX uses mail context that allows configuration directives for all aspects of proxying mail connections.

The mail context is defined in the main context i.e at the same level as the HTTP context.


# main context
mail {
       server_name mail.example.com;
       auth_http   localhost:9000/cgi-bin/nginxauth.cgi;
       proxy_pass_error_message on;
       ...
}
http {

}
...
...

NGINX Config File – If context

The if-context allows conditional execution of directives defined within it. The context is same as an if statement in any other programming languages. The if context should be avoided as far as possible due to some limitations of it which is discussed here.


http {
        server {
                     location /some_url {
                     if (test_condition) {
                          # do some stuff here
                   }

         }
    }
}

Limit_except Context

The limit_except context allows preventing the use of all HTTP methods except the ones that you explicitly allow. In the location context, you can restrict the usage of certain HTTP methods like forbidding clients from sending POST requests using limit_except context.

Just define two elements in a limit_except context, first one is the methods that are allowed and second is the audience those are affected by the restriction.


...
...
location /wp-admin/ { 
    limit_except GET { 
      allow 127.0.0.1; 
      deny all; 
    } 
}
...
...

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

NGINX Config File Miscellaneous Contexts

Apart from the context those we have discussed so far, 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 is used to split clients request into two or more categories. This context is defined inside http context and are mainly used for A/B testing.
  • geo: The geo context is used to categorize client IP addresses. It maps the value of a variable depending on the connecting IP address.
  • charset_map: The charset_map context is used to add specific charset to the “Content-Type” response header field. In addition, using the context one can convert data from one charset to another with some limitations.
  • map: The map context creates variables whose values depend on values of other variables and are defined in the http context.
  • perl / perl_set: The perl context is used to implement location and variable handlers in Perl and insert Perl calls into SSI. Further, using perl_set context one can install a Perl handler for a specific variable.
  • types: The types context is used to map MIME types with correct file extensions. The types context may appear in the http, server or location context. The default mime types are loaded through NGINX core configuration file nginx.conf.

Summary

Now that you have a basic idea of NGINX configuration file, use the context described above to fine tune the configuration in your environments. While defining configuration for NGINX, always define the common directives in the higher context if it is available and if necessary override them in the lower context. This will avoid unnecessary code repetition in the configuration file.

Lastly using If context may result in an unexpected result that is already mentioned earlier. NGINX provides a lot of directives and using it you can get the same result without using if context. If you really want to use if-context then deploy the configuration after heavy testing.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages