Understanding the Nginx Configuration File Structure and Configuration Contexts

Understanding the Nginx Configuration File Structure and Configuration Contexts

Understanding Nginx Configuration Contexts

Introduction

Nginx is a high-performance web server that handles the traffic of some of the largest websites on the internet. It excels at serving static content and handling multiple concurrent connections.

While many users are aware of Nginx's capabilities, some of the conventions found in Nginx configuration files frequently confuse new users. In this guide, we will discuss the basic structure of a Nginx configuration file as well as some guidelines for designing your files.

This guide will cover the basic structure found in the main Nginx configuration file. The location of this file will vary depending on how you installed the software on your machine. For many distributions, the file will be located at /etc/nginx/nginx.conf . If it does not exist there, it may also be at. /usr/local/nginx/conf/nginx.conf or /usr/local/etc/nginx/nginx.conf.

The Core Contexts

When you look at the main configuration file, one of the first things you should notice is that it appears to be organised in a tree-like structure, defined by sets of brackets (that look like and). The areas defined by these brackets are known as "contexts" in Nginx because they contain configuration details that are separated according to their area of concern. Essentially, these divisions provide an organisational structure as well as some conditional logic to determine whether or not to apply the configurations contained within.

These are the contexts that comprise the major structure of an Nginx configuration:

**The Main Context ** ```

The main context is here, outside any other contexts

. . . context { . . . } ``` The main context represents the most comprehensive environment for configuring Nginx. It is used to configure basic details that affect the entire application. While the directives in this section have an impact on lower contexts, many of them aren't inherited because they can't be overridden at lower levels.

The user and group to run the worker processes as, the number of workers, and the file to save the main process's PID are all common details configured in the main context. You can also specify worker CPU affinity and the "niceness" of worker processes. At this level, you can specify the default error file for the entire application (this can be overridden in more specific contexts).

The Events Context

# main context
events {
    # events context
    . . .
}

The "events" context is part of the "main" context. It is used to configure global options that affect how Nginx handles connections in general. Within the Nginx configuration, only one events context can be defined.

Because Nginx employs an event-based connection processing model, the directives defined in this context govern how worker processes handle connections. Directives found here are mostly used to either choose the connection processing technique to use or to change how these methods are implemented. The HTTP Context ```

main context

events { # events context . . . } http { # http context . . . } ``` The "http" context will hold the majority of the configuration when configuring Nginx as a web server or reverse proxy. This context will include all directives and other contexts required to define how the programme will handle HTTP or HTTPS connections.

Because the http context is a sibling of the events context, they should be listed alongside each other rather than nested. They are both offspring of the primary context.

Lower contexts become more specific about how to handle requests, but directives at this level control the defaults for each virtual server defined within. Depending on how you want the inheritance to work, a large number of directives are The Server Context

# main context
http {
    # http context
    server {
        # first server context
    }
    server {
        # second server context
    }
}

Within the "http" context, the "server" context is declared. This is the first time we've seen nested, bracketed contexts. It's also the first context to support multiple declarations.

The general format for server context might look like this. Keep in mind that these are in the http context:

The reason for allowing multiple server context declarations is that each instance defines a unique virtual server to handle client requests. You can have as many server blocks as you need, each with its own set of connections.

Because of the possibility and likelihood of multiple server blocks, this is the first context type for which Nginx must use a selection algorithm to make decisions. Because each client request will be handled according to the configuration defined in a single server context, Nginx must determine which server context is most appropriate based on the request's details.

The Location Context ```

main context

server {
# server context location /match/criteria { # first location context } location /other/criteria { # second location context location nested_match { # first nested location } location other_nested { # second nested location } } } ``` The next context you will encounter on a regular basis is the location context. Location contexts and server contexts share many relational characteristics. For example, multiple location contexts can be defined, with each location handling a specific type of client request and each location being chosen by matching the location definition against the client request using a selection algorithm.

While the directives that determine whether to select a server block are defined within the server context, the component that determines a location's ability to handle a request is defined within the location definition (the line that opens the location block).

Location blocks exist within server contexts and, unlike server blocks, can be nested within other location blocks. This can be useful for capturing a specific subset of traffic with a more general location context and then further processing it with more specific criteria and additional contexts inside:

While server contexts are chosen based on the requested IP address/port combination and the host name in the "Host" header, location blocks divide up request handling within a server block based on the request URI. The request URI is the string that follows the domain name or IP address/port combination in the request.

The contexts below are not as common as the ones we have discussed so far, but are still very useful to know about.

**The Upstream Context : ** The upstream context is used to define and configure “upstream” servers. Basically, this context defines a named pool of servers that Nginx can then proxy requests to. This context will likely be used when you are configuring proxies of various types

**The Mail Context : ** The main function of the mail context is to provide an area for configuring a mail proxying solution on the server. Nginx has the ability to redirect authentication requests to an external authentication server. It can then provide access to POP3 and IMAP mail servers for serving the actual mail data. The mail context can also be configured to connect to an SMTP Relayhost if desired.

The If Context : The “if” context can be established to provide conditional processing of directives defined within. Like an if statement in conventional programming, the if directive in Nginx will execute the instructions contained if a given test returns “true”.

The Limit_except Context : The limit_except context is used to restrict the use of certain HTTP methods within a location context. For example, if only certain clients should have access to POST content, but everyone should have the ability to read content, you can use a limit_except block to define this requirement.

**Main and server contexts Example **

## main
worker processes auto;

error_log /path/to/error error;

http {
    server{

        listen 80;
        server_name mydomain.com www.mydomain.com;

        location / {
            root /path/to/folder;
            index index.html;
        }
    }
}

Redirecting to HTTPS

http {
    server {

        listen 443 ssl;
        server_name mydomain.com www.mydomain.com;

        location / {
            root /path/to/root;
            index index.html;
        }

        ssl_certificate /path/to/certificate;
        ssl_certificate_key /path/to/key;
    }

    server {

    listen 80;
    server_name mydomain.com www.mydomain.com;

    return 301 https://$server_name$request_uri;
    }
}

**Proxy Server Example: ** ``` worker processes auto;

error_log /path/to/error error;

http { server { listen 443 ssl;

server_name mydomain.com mydomain.com;

location /static/ { alias /path/to/root; }

location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; I proxy set_header X-Forwarded-For $proxy_add x_forwarded_ for; } } } ``` Some resources:

Setting up Django and your web server with uWSGI and nginx

How to Set Up a Website on Nginx and Linux

Django with Nginx, Gunicorn