nginx.conf

nginx.conf is a configuration file used by the Nginx web server.

nginx.conf contains all the configuration for a Nginx web server in a text-based configuration file.

Default location

The default location of nginx.conf is /etc/nginx/nginx.conf.

However, different Linux distributions and other operating systems may place the configuration file in different locations:

  • /usr/local/nginx/conf/nginx.conf
  • /usr/local/etc/nginx/nginx.conf

Example

Here are some examples of nginx.conf files:

 server {
        listen 80;
        root /var/www/mydomain1;
        index index.html;
        server_name mydomain1.com;
    }
    server {
        listen 80;
        root /var/www/mydomain.com; 
        index index.html;
        server_name mydomain2.com;
    }

    server {
        client_max_body_size 8M; # 8M is 8Mb
    
        # other lines
    }

Structure

A nginx.conf file uses key-value pairs called directivesgrouped by contexts.

The divisions marked by these brackets ( { }) are called contextswhile the directivessite inside the contexts.

Nginx will throw an error if a directive is used in the wrong context.

Contexts

There are multiple contexts you can use in the Nginx configuration file:

  • The HTTP context. The http {} context defines how the Nginx server processes HTTP & HTTPS requests.

      http {
        ....
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        ....
      }
  • The events context:

      events {
        ....
      }
  • The server context. The server {} context defines the virtual context that responds to a request. The server context can be written within a http context:

      http {
        ....
        server {
            ....
            listen 80 default_server;
            ....
        }
      }

Directives

Directives can be:

  • Simple directives. The name and parameter are separated by space and ending with a semicolon ;.
  • Block directives. Multiple related directives can be grouped together enclosed by curly braces { }.

Simple Directives

An example of a simple directive in

user             www;

Blocks Directives

An example of a block directive:

server {
    listen              80;
    server_name         mydomain.com;

    location / {
        proxy_pass      http://mydomain.com;
    }
}

Another example of a block directive:

events {
    worker_connections  4096; ## Example of comment
}