Skip to content

Nginx HTTP Module and Configuration

Posted on:July 10, 2015

Nginx’s HTTP module comes with its own set of directives and structure blocks.

Structure Blocks

http

The http block acts as the overarching block for all directives and sub-blocks.

server

A server block defines a website, as identified by a hostname (or many), or in Nginx parlance, a virtual host. server blocks cannot be placed outside of a http block.

location

A location block allows you to define settings for specific locations in a website. location blocks can be placed in a server block or nested within another location block.

A location block is specified with a pattern that will be matched against the requested URI. This pattern can be quite complex, involving location modifiers.

= modifier

This modifier means the URI must match the pattern exactly. Only simple strings can be specified (no regular expressions).

No modifier

This modifier means the URI must begin with the pattern. Only simple strings can be specified (no regular expressions).

~ modifier

This modifier means the URI must match the pattern, and is case sensitive. Regular expressions are allowed.

~* modifier

This modifier means the URI must match the pattern, and is case insensitive. Regular expressions are allowed.

^~ modifier

This modifier behaves the same as no modifier, except that Nginx will stop searching for other patterns if it has matched a location block with this modifier (see below for search order and priority).

@ modifier

This modifier is used to define a named location block, which can only be accessed internally by try_files or error_page (see below).

As an example, given a pattern of /abcd or ^/abcd$:

Search order and priority

Different modifiers have different priorities when Nginx is searching for a location block that matches a particular URI.

In order from most important to least important:

  1. Matching on the = modifier
  2. Matching exactly on no modifier
  3. Matching on the ^~ modifier
  4. Matching on the ~ and ~* modifiers
  5. Matching on no modifier

Module Directives

Socket and host configuration

listen

Context: server

Sets the address and port for IP, or path for a UNIX-domain socket. If the address is left out, then a wildcard (*) is assumed. If the port is left out, port 80 is assumed (unless the master process is run without root privileges, in which case port 8000 will be assumed).

Also accepts ssl and spdy parameters for SSL and SPDY (SPDY practically requires SSL) connections respectively:

listen 443 ssl spdy;

More information on configuring Nginx for HTTPS.

server_name

Context: server

Sets the hostname for the server block. Nginx will match against all server blocks’ server_name directive, choosing the first block that matches. If none of them match, then Nginx will match against the listen directive’s address parameter (see above).

Allows wildcards and regex. Allows multiple hostnames.

tcp_nodelay

Context: http, server, location Default: on

Enables or disables the TCP_NODELAY socket option for keep-alive connections. TCP implements a mechanism, using an algorithm called Nagle’s algorithm, that delays sending data over the packet by some empirically determined time (Linux sets it at 200ms) to reduce the number of overly-small packets being sent out and causing network congestion. In other words, it temporally buffers the data being sent. However, this feature is somewhat irrelevant nowadays, with much more bandwidth available on the interwebs. Recommended to keep on (disable Nagle’s algorithm).

tcp_nopush

Context: http, server, location Default: off

The tcp_nopush option corresponds to the TCP_CORK option in the Linux TCP stack. TCP_CORK, like TCP_NODELAY, buffers data by blocking packets from being sent through the socket until the amount of data in the window reaches the Maximum Segment Size (MSS)1. Disabling tcp_nopush will allow partial frames to be sent. This option is only affected when the sendfile directive is enabled.

sendfile

Context: http, server, location Default: off

One of the reasons why Nginx is famous for its speed in serving static files is due to the sendfile option, which uses the OS’s sendfile(2) function. The Linux’s man page explains it best:

sendfile() copies data between one file descriptor and another. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read(2) and write(2), which would require transferring data to and from user space.

The sendfile() function itself takes 4 arguments, the first two of which are the file descriptors for reading (in_fd) and writing (out_fd). However, the man page specifies that:

The in_fd argument must correspond to a file which supports mmap(2)-like operations (i.e., it cannot be a socket).

Thus, sendfile() cannot be used for Unix sockets. That means sendfile() doesn’t work in conjunction with Unicorn for serving Rails applications. Still, you can and should enable sendfile for serving static files.

tcp_nodelay, tcp_nopush and sendfile can work in conjunction. tcp_nopush ensures that only full packets are sent out, reducing network (header) overhead. When the last packet is sent, tcp_nopush is disabled by Nginx, and tcp_nodelay allows the the packet to be sent immediately, instead of waiting 200ms.

reset_timedout_connection

Context: http, server, location Default: off

Turning this on will free up the memory assigned to the socket if the socket connection times out. Recommended to turn on.

Paths and Documents

root

Context: http, server, location, if

The location of the document root containing the files to be served.

alias

Context: location

Aliases a specified location to another location, for example:

server {
  server_name localhost;
  location /test/ {
    alias /test2/
  }
}

Requests to http://localhost/test/ will be served from http://localhost/test2/

error_page

Context: http, server, location, if

Allows you to specify error pages for 4-500 errors:

error_page 404 /404.html
error_page 500 /server_error.html

index

Context: http, server, location

Defines the default page to serve if no filename is specified in the request. If autoindex is enabled, then Nginx will attempt to index the files automatically.

try_files

Context: server, location

A directive that specifies the files to attempt to serve within a server or location block. A contrived example demonstrates how try_files works:

location / {
  try_files $uri $uri.html $uri.php $uri.xml @proxy;
}

# the following is a "named location block"

location @proxy {
  proxy_pass 127.0.0.1:8080;
}

try_files $uri is the “normal” behavior, where Nginx tries to locate the document with the exact specified URI. If it does not correspond to any existing file, Nginx will try to append .html to the URI and try, then with .php, then .xml, in that order. If all of these fail, then it defers the request to another location block. Another location block, if specified, must be the last argument.

Client requests

keepalive_requests

Context: http, server, location Default: 100

Defines the maximum number of requests that Nginx allows per keep-alive connection.

keepalive_timeout

Context: http, server, location Default: 75

Defines the maximum number of seconds Nginx will wait for before closing a keep-alive connection. It also accepts an optional second argument that Nginx will use to add a Keep-Alive: timeout= HTTP header:

keepalive_timeout 45 30;

send_timeout

Context: http, server, location Default: 60

Defines the maximum number of seconds Nginx will wait between two write operations to the client before closing the inactive connection.

client_body_timeout

Context: http, server, location Default: 60

Defines the maximum number of seconds Nginx will wait between two read operations from the client before responding with a 408 Request Timeout error.

client_max_body_size

Context: http, server, location Default: 1m

Defines the maximum size of a client request body. Needs to be set appropriately if user file uploads are expected.

MIME types

Before serving a file, Nginx will inspect its file extension to determine what value to set in the response’s Content-Type header. Nginx already includes a basic set of MIME types in its default configuration file: include mime.types;. To handle file extensions not covered in mime.types, one can include a types block:

types {
  image/jpeg jpg;
  application/json json;
}

Limits and restrictions

limit_rate

Context: http, server, location, if Default: No limit

Limits the transfer rate of client connections.

limit_rate_after

Context: http, server, location, if Default: None

Sets the amount of data to allow transferring before the limit_rate directive takes effect.

internal

Prevents external requests from accessing the specific location block:

location /admin/ {
  internal;
}

File processing and caching

open_file_cache

Context: http, server, location Default: Off

Enables Nginx caching for file descriptors. It accepts two arguments: max=X, where X refers to the maximum number of entries that can be cached, and inactive=Y, where Y refers to the number of seconds a cache entry should be stored. Y defaults to 60 seonds, meaning that cache entries will be cleared after 60 seconds, unless the open_file_cache_min_uses directive is specified (see below).

open_file_cache_errors

Context: http, server, location Default: Off

Enables Nginx caching for errors related to file lookups, such as incorrect file permissions or non-existence of files. This is so that Nginx doesn’t have to repeatedly attempt accessing files it cannot serve.

open_file_cache_min_uses

Context: http, server, location Default: 1

This directive allows you to tell Nginx not to remove file descriptors from the cache if its accessed more than a certain number of times, as defined by this directive:

open_file_cache_min_uses 2;

open_file_cache_valid

Context: http, server, location Default: 60

Defines the number of seconds Nginx will wait for before revalidating a cached entry.

Other directives

server_tokens

Context: http, server, location Default: On

Tells Nginx whether to include its version number in the response.

underscores_in_headers

Context: http, server Default: Off

Allow or disallow underscores in custom HTTP header names (such as X_AUTH_TOKEN).

Footnotes

  1. MSS is usually 40 or 60 bytes smaller than the Maximum Transmission Unit (MTU), since it doesn’t account for the TCP header or IP header.