Nginx Configurations An Overview

Create 2023-21-03

mockup

by Georg R. Pollak

Mastering Nginx Configuration

Nginx, a powerful and versatile web server that provides and alternative to Appache. It offers extensive configuration options to tailor its behavior to your specific needs. This post provides and overview over the most important commands and configuration files to host you own webpage.

Installation

Before we start, ensure Nginx is installed on your server. We recommend using the snap package for easy installation and updates:

apt update
apt install nginx
systemctl start nginx

Commands

Test Configuration

Before applying changes, it's crucial to validate your Nginx configuration. The following command checks for syntax errors:

nginx -t

Reload Configurations

Reloads the Nginx configuration without stopping the server. It's a more graceful way to apply changes without causing downtime.

systemctl reload nginx

Configuration Files

Enabling a Configuration File

To activate a configuration file, create a symbolic link from `sites-available` to `sites-enabled`:

sudo ln -s /etc/nginx/sites-available/my_configuration /etc/nginx/sites-enabled/

Variables $

Nginx provides some predefined dynamic variables that can be used:

VariableDescription
$http_user_agentIs the browser of the client as a text string.
$remote_addrThe IP address of the client making the request.
$hostStores the value of the HTTP host header from the client's request - it represents the domain name used to access the server.
$request_uriContains the full original request URI (including query parameters) sent by the client.
$uriContains the request URI without query parameters.
$argsContains the query string portion of the request URI.
$server_nameRepresents the server name as defined in the server_name directive.
$schemeHolds the request scheme (HTTP or HTTPS).
$document_rootRepresents the root directory for serving files as defined in the root directive.
$request_methodContains the HTTP method used in the client's request (e.g., GET, POST, etc.).
$server_portStores the port number on which the server is listening.
$http_<header>You can access any HTTP header from the client's request using this notation, where <header> is the name of the header in lowercase with hyphens replaced by underscores. For example, $http_accept_language holds the value of the Accept-Language header.
$query_stringHolds the query string portion of the request URI, excluding the question mark.

Block Directives {}

server {}

Defines a virtual server block. Each block specifies how Nginx should handle incoming requests for a specific server name, IP address, and/or port. This allows you to configure multiple websites or applications to be served by the same Nginx instance, each with its settings and behavior.

Directives
  • server_name: Associates a domain name or IP address with an Nginx server block.
server {
    server_name ip/domain_name;
}
  • listen port default_server;;: Restricts incoming traffic to a certain port.
server {
    listen portnumber default_server;;      # IPv4
    listen [::]:portnumber; # for IPv6
}

Note: The `default_server` makes this the default server that handles requests that do not specify a port.

  • root - default=/usr/local/nginx: Specifies the root directory / that can be used, for example, in location directives.
  • location: Defines how the server should respond to requests for specific URLs or URL patterns.
location path {
    # Configuration directives specific to this location
}

Note: `path` is the path appended to our server, i.e., `www.myserver.com/path`.

Configuration Directives
  • root: Can be used to overwrite the root directive from a parent scope.
location ~ \.(mp3|mp4) {
    root /www/media;
}
  • Static Files Aliases: Can be used to define aliases for URLs or URL patterns.
location /images/ {
    alias /var/www/src/;
}

This will transform `www.myserver.com/images` to `www.myserver.com/src/`, which will search for and index files at `root/src/`.

  • proxy_pass: This is one of the most important directives and configures nginx to work as a reverse proxy, that sits between client devices and backend servers.
location path {
    proxy_pass http://127.0.0.1:8000;
}
  • proxy_set_header: Is used to set HTTP headers that will be passed from the Nginx reverse proxy server to the backend server when forwarding requests.
location path {
    proxy_set_header key value;
}
  • X-Real-IP: Can be used to set/forward the client's IP address.
location path {
    proxy_set_header X-Real-IP $remote_addr;
}
  • Host: Can be used to set/forward the client's HTTP host header.
location path {
    proxy_set_header Host $http_host;
}
  • X-Forwarded-For: Can be used to set/forward the X-Forwarded-For header IP addresses. It is a list of IP addresses that can be used when requests are being passed through intermediary proxies or load balancers. Each proxy adds its IP to the header. The X-Forwarded-For variable is often used to make sure that a request moves properly through the proxy chain.
location path {
    proxy_set_header X-Real-IP $proxy_add_x_forwarded_for;
}
  • X-NginX-proxy: Can be used to set X-NginX-proxy header to indicate to the backend-server that the request comes from the nginx server.
location path {
    proxy_set_header X-NginX-proxy true;
}
  • proxy_redirect: Is used in Nginx configuration to control how the response headers in proxied responses are modified before they are sent back to the client.
location path {
    proxy_redirect [default | off | redirect replacement];
}
  • default: This value is used when the server responds with a redirect, and the response headers need to be modified. The proxy_redirect directive with this value uses default settings.
  • off: This value disables header modifications for all types of responses.
  • redirect replacement: This value is used to specify a string replacement for modifying the response headers.
  • try_files: Is used to define a fallback mechanism for handling requests in case a specific file or directory is not found.

Example:

  1. Check first for a file with the exact $uri.
  2. If this file does not exist, check for a folder with the name of the $uri.
  3. If neither a file nor a directory with the $uri exist, try to forward the request to the backend server.
location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    proxy_pass http://backend.example.com;
}
  • Named Locations @location: Named locations can be used as placeholders to be used, for example, in try_files blocks.
location @backend {
    proxy_pass http://backend.example.com;
}

http {}

The http {} directive is a top-level directive in Nginx configuration to enclose all server blocks and specify HTTP/HTTPS traffic only. Using the http directive is a recommended practice for configurations with multiple server blocks or more complex setups but is not strictly required.

http {
    # HTTP server block
    server {
        listen 80;
        server_name example.com;
        # Other HTTP-specific configuration here...
    }

    # HTTPS server block
    server {
        listen 443 ssl;
        server_name example.com;
        ssl_certificate /path/to/ssl_certificate.crt;
        ssl_certificate_key /path/to/ssl_certificate_key.key;
        # Other HTTPS-specific configuration here...
    }

    # Other HTTP/HTTPS-related configuration here...
}

events {}

The events {} directive defines directives related to the Nginx event loop, which is responsible for handling connections and events such as client requests.

Directives

  • Worker Connections: Defines the maximum number of simultaneous connections that a worker process can handle. Nginx will reject additional connections, and they will receive connection timeouts.
events {
    worker_connections 1024;
}
  • worker_processes: Defines the number of worker processes that Nginx will spawn. The value can be set to the number of CPU cores or a specific number.
events {
    worker_processes 4/max;
}

In conclusion, mastering Nginx configuration opens up a world of possibilities for optimizing your web server's performance and enhancing security. By understanding these commands and configuration options, you can tailor Nginx to meet the specific requirements of your web applications.