OpenBSD manual page server

Manual Page Search Parameters

NGINX.CONF(5) File Formats Manual NGINX.CONF(5)

nginx.confnginx daemon configuration file

nginx(8) (pronounced “engine x”) is an HTTP and reverse proxy server, as well as a mail proxy server. It is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.

The configuration file consists of a list of configuration directives:

list ::= [directive] [opt-ws] [list]

Lists may be empty, they may contain leading and trailing whitespace and comments, and they may contain whitespace and comments between directives. Such whitespace is semantically insignificant.

The syntax of a configuration directive is:

directive ::= keyword ws arguments [ws] ";" | context

In this case, whitespace is required to separate the keyword from the arguments. A context may not be followed by a semicolon, but after every other directive, a semicolon is required, even at the end of a list.

As a special cases of a configuration directive, the syntax of a configuration context is:

context ::= keyword [ws] "{" [list] "}"

Contexts may be nested, and they freely intermix with other directives on each nesting level.

The syntax of whitespace is:

ws ::= ws-char [opt-ws]
ws-char ::= ⟨space⟩ | ⟨tab⟩ | ⟨newline⟩
opt-ws ::= (comment | ws-char) [opt-ws]
comment ::= "#" [⟨non-newline character⟩ ...] ⟨newline⟩

Comments start with a hash character and extend to the end of the line. They can start at the beginning of a line, after the semicolon or closing brace at the end of a directive, or after any whitespace character, even in the middle of a directive.

In the following, all keywords are listed, and their arguments are explained.

on |
default: on
 
context: events
 

If accept_mutex is enabled, worker processes will accept new connections by turn. Otherwise, all worker processes will be notified about new connections, and if volume of new connections is low, some of the worker processes may just waste system resources. The use of rtsig connection processing method requires accept_mutex to be enabled.

time
default: 500ms
 
context: events
 

If accept_mutex is enabled, specifies the maximum time during which a worker process will try to restart accepting new connections if another worker process is currently accepting new connections.

on |
default: on
 
context: main
 

Determines whether nginx should become a daemon. Mainly used during development.

address | CIDR |
default:
 
context: events
 

Enables debugging log for selected client connections. Other connections will use logging level set by the error_log directive. Debugged connections are specified by IPv4 or IPv6 (1.3.0, 1.2.1) address or network. A connection may also be specified using a hostname. For connections using UNIX-domain sockets (1.3.0, 1.2.1), debugging log is enabled by the unix: parameter.

events {
    debug_connection 127.0.0.1;
    debug_connection localhost;
    debug_connection 192.0.2.0/24;
    debug_connection ::1;
    debug_connection 2001:0db8::/32;
    debug_connection unix:;
    ...
}

For this directive to work, nginx needs to be built with --with-debug.

abort |
default:
 
context: main
 

This directive is used for debugging. When internal error is detected, e.g. the leak of sockets on restart of working processes, enabling debug_points leads to a core file creation (abort) or to stopping of a process (stop) for further analysis using a system debugger.

file | | :server=address [, parameter=value] [debug | info | notice | warn | error | crit | alert | emerg]
default: logs/error.log error
 
context: main, http, server, location
 

Configures logging. Several logs can be specified on the same level (1.5.2). The first parameter defines a file that will store the log. The special value stderr selects the standard error file. Logging to syslog can be configured by specifying the syslog: prefix. The second parameter determines the level of logging. Log levels above are listed in the order of increasing severity. Setting a certain log level will cause all messages of the specified and more severe log levels to be logged. For example, the default level error will cause error, crit, alert, and emerg messages to be logged. If this parameter is omitted then error is used. For debug logging to work, nginx needs to be built with --with-debug. The following parameters configure logging to syslog:

=address
Defines an address of a syslog server. An address can be specified as a domain name or IP address, and an optional port, or as a UNIX-domain socket path specified after the unix: prefix. If port is not specified, the port 514 is used. If a domain name resolves to several IP addresses, the first resolved address is used.
=string
Sets facility of syslog messages, as defined in RFC 3164. Facility can be one of kern, user, mail, daemon, auth, intern, lpr, news, uucp, clock, authpriv, ftp, ntp, audit, alert, cron, local0 .. local7. Default is local7.
=string
Sets tag of syslog messages. Default is "nginx".

Example syslog configuration:

error_log syslog:server=192.168.1.1 debug;
error_log syslog:server=unix:/var/log/nginx.sock;
error_log syslog:server=[2001:db8::1]:12345,facility=local7,tag=nginx error;
variable[=value]
default: TZ
 
context: main
 

By default, nginx removes all environment variables inherited from its parent process except the TZ variable. This directive allows preserving some of the inherited variables, changing their values, or creating new environment variables. These variables are then:

  • inherited during a live upgrade of an executable file;
  • used by the Module ngx_http_perl_module module;
  • used by worker processes. One should bear in mind that controlling system libraries in this way is not always possible as it is common for libraries to check variables only during initialization, well before they can be set using this directive. An exception from this is an above mentioned live upgrade of an executable file.

The TZ variable is always inherited and available to the Module ngx_http_perl_module module, unless it is configured explicitly. Usage example:

env MALLOC_OPTIONS;
env PERL5LIB=/data/site/modules;
env OPENSSL_ALLOW_PROXY_CERTS=1;

The NGINX environment variable is used internally by nginx and should not be set directly by the user.

{...}
default:
 
context: main
 

Provides the configuration file context in which the directives that affect connection processing are specified.

file | mask
default:
 
context: any
 

Includes another file, or files matching the specified mask, into configuration. Included files should consist of syntactically correct directives and blocks. Usage example:

include mime.types;
include vhosts/*.conf;
file
default: logs/nginx.lock
 
context: main
 

nginx uses the locking mechanism to implement accept_mutex and serialize access to shared memory. On most systems the locks are implemented using atomic operations, and this directive is ignored. On other systems the lock file mechanism is used. This directive specifies a prefix for the names of lock files.

on |
default: on
 
context: main
 

Determines whether worker processes are started. This directive is intended for nginx developers.

on |
default: off
 
context: events
 

If multi_accept is disabled, a worker process will accept one new connection at a time. Otherwise, a worker process will accept all new connections at a time. The directive is ignored if kqueue connection processing method is used, because it reports the number of new connections waiting to be accepted. The use of rtsig connection processing method automatically enables multi_accept.

on |
default: off
 
context: main
 

Enables or disables the use of just-in-time compilation (PCRE JIT) for the regular expressions known by the time of configuration parsing. PCRE JIT can speed up processing of regular expressions significantly. The JIT is available in PCRE libraries starting from version 8.20 built with the --enable-jit configuration parameter. When the PCRE library is built with nginx (--with-pcre=),the JIT support is enabled via the --with-pcre-jit configuration parameter.

file
default: nginx.pid
 
context: main
 

Defines a file that will store the process ID of the main process.

device
default:
 
context: main
 

Defines the name of the hardware SSL accelerator.

interval
default:
 
context: main
 

Reduces timer resolution in worker processes, thus reducing the number of () system calls made. By default, gettimeofday() is called each time a kernel event is received. With reduced resolution, gettimeofday() is only called once per specified interval. Example:

timer_resolution 100ms;

Internal implementation of the interval depends on the method used:

method
default:
 
context: events
 

Specifies the connection processing method to use. There is normally no need to specify it explicitly, because nginx will by default use the most efficient method.

user [group]
default: nobody nobody
 
context: main
 

Defines user and group credentials used by worker processes. If group is omitted, a group whose name equals that of user is used.

number
default: 32
 
context: events
 

When using aio with the epoll connection processing method, sets the maximum number of outstanding asynchronous I/O operations for a single worker process.

number
default: 512
 
context: events
 

Sets the maximum number of simultaneous connections that can be opened by a worker process. It should be kept in mind that this number includes all connections (e.g. connections with proxied servers, among others), not only connections with clients. Another consideration is that the actual number of simultaneous connections cannot exceed the current limit on the maximum number of open files, which can be changed by worker_rlimit_nofile.

cpumask ...
default:
 
context: main
 

Binds worker processes to the sets of CPUs. Each CPU set is represented by a bitmask of allowed CPUs. There should be a separate set defined for each of the worker processes. By default, worker processes are not bound to any specific CPUs. For example,

worker_processes    4;
worker_cpu_affinity 0001 0010 0100 1000;

binds each worker process to a separate CPU, while

worker_processes    2;
worker_cpu_affinity 0101 1010;

binds the first worker process to CPU0/CPU2, and the second worker process to CPU1/CPU3. The second example is suitable for hyper-threading. The directive is only available on FreeBSD and Linux.

number
default: 0
 
context: main
 

Defines the scheduling priority for worker processes like it is done by the nice command: a negative number means higher priority. Allowed range normally varies from -20 to 20. Example:

worker_priority -10;
number |
default: 1
 
context: main
 

Defines the number of worker processes. The optimal value depends on many factors including (but not limited to) the number of CPU cores, the number of hard disk drives that store data, and load pattern. When one is in doubt, setting it to the number of available CPU cores would be a good start (the value auto will try to autodetect it). The auto parameter is supported starting from versions 1.3.8 and 1.2.5.

size
default:
 
context: main
 

Changes the limit on the largest size of a core file (RLIMIT_CORE) for worker processes. Used to increase the limit without restarting the main process.

number
default:
 
context: main
 

Changes the limit on the maximum number of open files (RLIMIT_NOFILE) for worker processes. Used to increase the limit without restarting the main process.

number
default:
 
context: main
 

On systems that support rtsig connection processing method, changes the limit on the number of signals that may be queued (RLIMIT_SIGPENDING) for worker processes. Used to increase the limit without restarting the main process.

directory
default:
 
context: main
 

Defines the current working directory for a worker process. It is primarily used when writing a core-file, in which case a worker process should have write permission for the specified directory.

on | |
default: off
 
context: http, server, location
 

Enables or disables the use of asynchronous file I/O (AIO) on FreeBSD and Linux. On FreeBSD, AIO can be used starting from FreeBSD 4.3. AIO can either be linked statically into a kernel:

options VFS_AIO

or loaded dynamically as a kernel loadable module:

kldload aio

In FreeBSD versions 5 and 6, enabling AIO statically, or dynamically when booting the kernel, will cause the entire networking subsystem to use the Giant lock, which can impact overall performance negatively. This limitation has been removed in FreeBSD 6.4-STABLE in 2009, and in FreeBSD 7. However, starting from FreeBSD 5.3 it is possible to enable AIO without the penalty of running the networking subsystem under a Giant lock-for this to work, the AIO module needs to be loaded after the kernel has booted. In this case, the following message will appear in /var/log/messages

WARNING: Network stack Giant-free, but aio requires Giant.
Consider adding 'options NET_WITH_GIANT' or setting debug.mpsafenet=0

and can safely be ignored. The requirement to use the Giant lock with AIO is related to the fact that FreeBSD supports asynchronous calls () and () when working with sockets. However, since nginx uses AIO only for disk I/O, no problems should arise. For AIO to work, sendfile needs to be disabled:

location /video/ {
    sendfile       off;
    aio            on;
    output_buffers 1 64k;
}

In addition, starting from FreeBSD 5.2.1 and nginx 0.8.12, AIO can also be used to pre-load data for ():

location /video/ {
    sendfile       on;
    tcp_nopush     on;
    aio            sendfile;
}

In this configuration, () is called with the SF_NODISKIO flag which causes it not to block on disk I/O, but, instead, report back that the data are not in memory. nginx then initiates an asynchronous data load by reading one byte. On the first read, the FreeBSD kernel loads the first 128K bytes of a file into memory, although next reads will only load data in 16K chunks. This can be changed using the read_ahead directive. On Linux, AIO can be used starting from kernel version 2.6.22. Also, it is necessary to enable directio, or otherwise reading will be blocking:

location /video/ {
    aio            on;
    directio       512;
    output_buffers 1 128k;
}

On Linux, directio can only be used for reading blocks that are aligned on 512-byte boundaries (or 4K for XFS). File's unaligned end is read in blocking mode. The same holds true for byte range requests and for FLV requests not from the beginning of a file: reading of unaligned data at the beginning and end of a file will be blocking. There is no need to turn off sendfile explicitly, as it is turned off automatically when directio is used.

path
default:
 
context: location
 

Defines a replacement for the specified location. For example, with the following configuration

location /i/ {
    alias /data/w3/images/;
}

on request of /i/top.gif, the file /data/w3/images/top.gif will be sent. The path value can contain variables, except $document_root and $realpath_root. If alias is used inside a location defined with a regular expression then such regular expression should contain captures and alias should refer to these captures (0.7.40), for example:

location ~ ^/users/(.+\.(?:gif |jpe?g |png))$ {
    alias /data/w3/images/$1;
}

When location matches the last part of the directive's value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}
on |
default: on
 
context: http, server, location
 

Allows disabling chunked transfer encoding in HTTP/1.1. It may come in handy when using a software failing to support chunked encoding despite the standard's requirement.

size
default: 8k | 16k
 
context: http, server, location
 

Sets buffer size for reading client request body. In case the request body is larger than the buffer, the whole body or only its part is written to a client_body_temp_path temporary file. By default, buffer size is equal to two memory pages. This is 8K on x86, other 32-bit platforms, and x86-64. It is usually 16K on other 64-bit platforms.

on | |
default: off
 
context: http, server, location
 

Determines whether nginx should save the entire client request body into a file. This directive can be used during debugging, or when using the $request_body_file variable, or the methods $r->request_body_file method of the module Module ngx_http_perl_module. When set to the value on, temporary files are not removed after request processing. The value clean will cause the temporary files left after request processing to be removed.

on |
default: off
 
context: http, server, location
 

Determines whether nginx should save the entire client request body in a single buffer. The directive is recommended when using the $request_body variable, to save the number of copy operations involved.

path [level1 [level2 [level3]]]
default: client_body_temp
 
context: http, server, location
 

Defines a directory for storing temporary files holding client request bodies. Up to three-level subdirectory hierarchy can be used under the specified directory. For example, in the following configuration

client_body_temp_path /spool/nginx/client_temp 1 2;

a path to a temporary file might look like this: /spool/nginx/client_temp/7/45/00000123457

time
default: 60s
 
context: http, server, location
 

Defines a timeout for reading client request body. The timeout is set only for a period between two successive read operations, not for the transmission of the whole request body. If a client does not transmit anything within this time, the 408 (Request Time-out) error is returned to the client.

size
default: 1k
 
context: http, server
 

Sets buffer size for reading client request header. For most requests, a buffer of 1K bytes is enough. However, if a request includes long cookies, or comes from a WAP client, it may not fit into 1K. If a request line or a request header field does not fit into this buffer then larger buffers, configured by the large_client_header_buffers directive, are allocated.

time
default: 60s
 
context: http, server
 

Defines a timeout for reading client request header. If a client does not transmit the entire header within this time, the 408 (Request Time-out) error is returned to the client.

size
default: 1m
 
context: http, server, location
 

Sets the maximum allowed size of the client request body, specified in the Content-Length request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.

size
default: 256
 
context: http, server
 

Allows accurate tuning of per-connection memory allocations. This directive has minimal impact on performance and should not generally be used.

mime-type
default: text/plain
 
context: http, server, location
 

Defines the default MIME type of a response. Mapping of file name extensions to MIME types can be set with the types directive.

size |
default: off
 
context: http, server, location
 

Enables the use of the O_DIRECT flag (FreeBSD, Linux), the F_NOCACHE flag (Mac OS X), or the () function (Solaris), when reading files that are larger than or equal to the specified size. The directive automatically disables (0.7.15) the use of sendfile for a given request. It can be useful for serving large files:

directio 4m;

or when using aio on Linux.

size
default: 512
 
context: http, server, location
 

Sets the alignment for directio. In most cases, a 512-byte alignment is enough. However, when using XFS under Linux, it needs to be increased to 4K.

 
on | [from=part]
default: off
 
context: http, server, location
 

Determines how symbolic links should be treated when opening files:

Symbolic links in the pathname are allowed and not checked. This is the default behavior.
If any component of the pathname is a symbolic link, access to a file is denied.
Access to a file is denied if any component of the pathname is a symbolic link, and the link and object that the link points to have different owners.
=part
When checking symbolic links (parameters on and if_not_owner), all components of the pathname are normally checked. Checking of symbolic links in the initial part of the pathname may be avoided by specifying additionally the from=part parameter. In this case, symbolic links are checked only from the pathname component that follows the specified initial part. If the value is not an initial part of the pathname checked, the whole pathname is checked as if this parameter was not specified at all. If the value matches the whole file name, symbolic links are not checked. The parameter value can contain variables.

Example:

disable_symlinks on from=$document_root;

This directive is only available on systems that have the () and () interfaces. Such systems include modern versions of FreeBSD, Linux, and Solaris. Parameters on and if_not_owner add a processing overhead. On systems that do not support opening of directories only for search, to use these parameters it is required that worker processes have read permissions for all directories being checked. The Module ngx_http_autoindex_module, Module ngx_http_random_index_module, and Module ngx_http_dav_module modules currently ignore this directive.

code ... [=[response]] uri
default:
 
context: http, server, location, if in location
 

Defines the URI that will be shown for the specified errors. error_page directives are inherited from the previous level only if there are no error_page directives defined on the current level. A uri value can contain variables. Example:

error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

Furthermore, it is possible to change the response code to another using the =response syntax, for example:

error_page 404 =200 /empty.gif;

If an error response is processed by a proxied server or a FastCGI server, and the server may return different response codes (e.g., 200, 302, 401 or 404), it is possible to respond with the code it returns:

error_page 404 = /404.php;

It is also possible to use redirects for error processing:

error_page 403      http://example.com/forbidden.html;
error_page 404 =301 http://example.com/notfound.html;

In this case, by default, the response code 302 is returned to the client. It can only be changed to one of the redirect status codes (301, 302, 303, and 307). If there is no need to change URI during internal redirection it is possible to pass error processing into a named location:

location / {
    error_page 404 = @fallback;
}
location @fallback {
    proxy_pass http://backend;
}

If uri processing leads to an error, the status code of the last occurred error is returned to the client.

on |
default: on
 
context: http, server, location
 

Enables or disables automatic generation of the ETag response header field for static resources.

{...}
default:
 
context: main
 

Provides the configuration file context in which the HTTP server directives are specified.

off | |
default: exact
 
context: http, server, location
 

Specifies how to compare modification time of a response with the time in the If-Modified-Since request header field:

the If-Modified-Since request header field is ignored (0.7.34);
exact match;
modification time of a response is less than or equal to the time in the If-Modified-Since request header field.
on |
default: on
 
context: http, server
 

Controls whether header fields with invalid names should be ignored. Valid names are composed of English letters, digits, hyphens, and possibly underscores (as controlled by the underscores_in_headers directive). A directive can be specified on the server level in the default server. In this case, its value will cover all virtual servers listening on the same address and port.

default:
 
context: location
 

Specifies that a given location can only be used for internal requests. For external requests, the client error 404 (Not Found) is returned. Internal requests are the following:

  • requests redirected by the error_page, index, random_index, and try_files directives;
  • requests redirected by the X-Accel-Redirect response header field from an upstream server;
  • subrequests formed by the include virtual command of the Module ngx_http_ssi_module module and by the Module ngx_http_addition_module module directives;
  • requests changed by the rewrite directive.

Example:

error_page 404 /404.html;
location /404.html {
    internal;
}

There is a limit of 10 internal redirects per request to prevent request processing cycles that can occur in incorrect configurations. If this limit is reached, the error 500 (Internal Server Error) is returned. In such cases, the rewrite or internal redirection cycle message can be seen in the error log.

none | browser ...
default: msie6
 
context: http, server, location
 

Disables keep-alive connections with misbehaving browsers. The browser parameters specify which browsers will be affected. The value msie6 disables keep-alive connections with old versions of MSIE, once a POST request is received. The value safari disables keep-alive connections with Safari and Safari-like browsers on Mac OS X and Mac OS X-like operating systems. The value none enables keep-alive connections with all browsers. Prior to version 1.1.18, the value safari matched all Safari and Safari-like browsers on all operating systems, and keep-alive connections with them were disabled by default.

number
default: 100
 
context: http, server, location
 

Sets the maximum number of requests that can be served through one keep-alive connection. After the maximum number of requests are made, the connection is closed.

timeout [header_timeout]
default: 75s
 
context: http, server, location
 

The first parameter sets a timeout during which a keep-alive client connection will stay open on the server side. The zero value disables keep-alive client connections. The optional second parameter sets a value in the Keep-Alive: timeout=time response header field. Two parameters may differ. The Keep-Alive: timeout=time header field is recognized by Mozilla and Konqueror. MSIE closes keep-alive connections by itself in about 60 seconds.

number size
default: 4 8k
 
context: http, server
 

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

method ... {...}
default:
 
context: location
 

Limits allowed HTTP methods inside a location. The method parameter can be one of the following: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH. Allowing the GET method makes the HEAD method also allowed. Access to other methods can be limited using the Module ngx_http_access_module and Module ngx_http_auth_basic_module modules directives:

limit_except GET {
    allow 192.168.1.0/32;
    deny  all;
}

Please note that this will limit access to all methods except GET and HEAD.

rate
default: 0
 
context: http, server, location, if in location
 

Limits the rate of response transmission to a client. The rate is specified in bytes per second. The zero value disables rate limiting. The limit is set per a request, and so if a client simultaneously opens two connections, the overall rate will be twice as much as the specified limit. Rate limit can also be set in the $limit_rate variable. It may be useful in cases where rate should be limited depending on a certain condition:

server {
    if ($slow) {
        set $limit_rate 4k;
    }
    ...
}

Rate limit can also be set in the X-Accel-Limit-Rate header field of a proxied server response. This capability can be disabled using the proxy_ignore_headers and fastcgi_ignore_headers directives.

size
default: 0
 
context: http, server, location, if in location
 

Sets the initial amount after which the further transmission of a response to a client will be rate limited. Example:

location /flv/ {
    flv;
    limit_rate_after 500k;
    limit_rate       50k;
}
off | |
default: on
 
context: http, server, location
 

Controls how nginx closes client connections. The default value on instructs nginx to lingering_timeout wait for and lingering_time process additional data from a client before fully closing a connection, but only if heuristics suggests that a client may be sending more data. The value always will cause nginx to unconditionally wait for and process additional client data. The value off tells nginx to never wait for more data and close the connection immediately. This behavior breaks the protocol and should not be used under normal circumstances.

time
default: 30s
 
context: http, server, location
 

When lingering_close is in effect, this directive specifies the maximum time during which nginx will process (read and ignore) additional data coming from a client. After that, the connection will be closed, even if there will be more data.

time
default: 5s
 
context: http, server, location
 

When lingering_close is in effect, this directive specifies the maximum waiting time for more client data to arrive. If data are not received during this time, the connection is closed. Otherwise, the data are read and ignored, and nginx starts waiting for more data again. The wait-read-ignore cycle is repeated, but no longer than specified by the lingering_time directive.

address[:port] [default_server] [ssl] [spdy] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on | off] [so_keepalive=on | off | [keepidle]:[keepintvl]:[keepcnt]]
 
port [default_server] [ssl] [spdy] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on | off] [so_keepalive=on | off | [keepidle]:[keepintvl]:[keepcnt]]
 
unix:path [default_server] [ssl] [spdy] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [so_keepalive=on | off | [keepidle]:[keepintvl]:[keepcnt]]

default: *:80 | *:8000
 
context: server
 

Sets the address and port for IP, or the path for a UNIX-domain socket on which the server will accept requests. Both address and port, or only address or only port can be specified. An address may also be a hostname, for example:

listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

IPv6 addresses (0.7.36) are specified in square brackets:

listen [::]:8000;
listen [::1];

UNIX-domain sockets (0.8.21) are specified with the unix: prefix:

listen unix:/var/run/nginx.sock;

If only address is given, the port 80 is used. If the directive is not present then either *:80 is used if nginx runs with the superuser privileges, or *:8000 otherwise. The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair. In versions prior to 0.8.21 this parameter is named simply default. The ssl parameter (0.7.14) allows specifying that all connections accepted on this port should work in SSL mode. This allows for a more compact configuration for the server that handles both HTTP and HTTPS requests. The spdy parameter (1.3.15) allows accepting SPDY connections on this port. Normally, for this to work the ssl parameter should be specified as well, but nginx can also be configured to accept SPDY connections without SSL. A listen directive can have several additional parameters specific to socket-related system calls. These parameters can be specified in any listen directive, but only once for a given address:port pair. In versions prior to 0.8.21, they could only be specified in the listen directive together with the default parameter.

=number
this parameter (0.8.44) sets the associated routing table, FIB (the SO_SETFIB option) for the listening socket. This currently works only on FreeBSD.
=number
sets the backlog parameter in the () call that limits the maximum length for the queue of pending connections. By default, backlog is set to -1 on FreeBSD and Mac OS X, and to 511 on other platforms.
=size
sets the receive buffer size (the SO_RCVBUF option) for the listening socket.
=size
sets the send buffer size (the SO_SNDBUF option) for the listening socket.
=filter
sets the name of accept filter (the SO_ACCEPTFILTER option) for the listening socket that filters incoming connections before passing them to (). This works only on FreeBSD and NetBSD_5.0+. Possible values are dataready and httpready.
instructs to use a deferred accept() (the TCP_DEFER_ACCEPT socket option) on Linux.
instructs to make a separate bind() call for a given address:port pair. This is useful because if there are several listen directives with the same port but different addresses, and one of the listen directives listens on all addresses for the given port (*:port), nginx will bind() only to "*:port". It should be noted that the () system call will be made in this case to determine the address that accepted the connection. If the backlog, rcvbuf, sndbuf, accept_filter, deferred, or so_keepalive parameters are used then for a given address: port pair a separate bind() call will always be made.
=on |
this parameter (0.7.42) determines (via the IPV6_V6ONLY socket option) whether an IPv6 socket listening on a wildcard address [::] will accept only IPv6 connections or both IPv6 and IPv4 connections. This parameter is turned on by default. It can only be set once on start. Prior to version 1.3.4, if this parameter was omitted then the operating system's settings were in effect for the socket.
=on | | [keepidle]:[keepintvl]:[keepcnt]
this parameter (1.1.11) configures the TCP keepalive behavior for the listening socket. If this parameter is omitted then the operating system's settings will be in effect for the socket. If it is set to the value on, the SO_KEEPALIVE option is turned on for the socket. If it is set to the value off, the SO_KEEPALIVE option is turned off for the socket. Some operating systems support setting of TCP keepalive parameters on a per-socket basis using the TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT socket options. On such systems (currently, Linux_2.4+, NetBSD_5+, and FreeBSD_9.0-STABLE), they can be configured using the keepidle, keepintvl, and keepcnt parameters. One or two parameters may be omitted, in which case the system default setting for the corresponding socket option will be in effect. For example,
so_keepalive=30m::10

will set the idle timeout (TCP_KEEPIDLE) to 30 minutes, leave the probe interval (TCP_KEEPINTVL) at its system default, and set the probes count (TCP_KEEPCNT) to 10 probes.

Example:

listen 127.0.0.1 default_server accept_filter=dataready backlog=1024;
[= | ~ | ~* | ^~] uri {...}
 
@ name {...}
default:
 
context: server, location
 

Sets configuration depending on a request URI. The matching is performed against a normalized URI, after decoding the text encoded in the "%XX" form, resolving references to relative path components "." and "..", and possible merge_slashes compression of two or more adjacent slashes into a single slash. A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding "~*" modifier (for case-insensitive matching), or the "~" modifier (for case-sensitive matching). To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used. location blocks can be nested, with some exceptions mentioned below. For case-insensitive operating systems such as Mac OS X and Cygwin, matching with prefix strings ignores a case (0.7.7). However, comparison is limited to one-byte locales. Regular expressions can contain captures (0.7.40) that can later be used in other directives. If the longest matching prefix location has the "^~" modifier then regular expressions are not checked. Also, using the = modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a / request happens frequently, defining "location=/" will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations. In versions from 0.7.1 to 0.8.41, if a request matched the prefix location without the "=" and "^~" modifiers, the search also terminated and regular expressions were not checked. Let's illustrate the above by an example:

location = / {
    [ configuration A ]
}
location / {
    [ configuration B ]
}
location /documents/ {
    [ configuration C ]
}
location ^~ /images/ {
    [ configuration D ]
}
location ~* \.(gif |jpg |jpeg)$ {
    [ configuration E ]
}

The "/" request will match configuration A, the "/index.html" request will match configuration B, the "/documents/document.html" request will match configuration C, the "/images/1.gif" request will match configuration D, and the "/documents/1.jpg" request will match configuration E. The @ prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations. If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, scgi_pass, uwsgi_pass, or memcached_pass, then in response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

location /user/ {
    proxy_pass http://user.example.com;
}
location = /user {
    proxy_pass http://login.example.com;
}
on |
default: on
 
context: http, server, location
 

Enables or disables logging of errors about not found files into error_log.

on |
default: off
 
context: http, server, location
 

Enables or disables logging of subrequests into access_log.

number
default:
 
context: http, server, location
 

Limits the maximum allowed number of ranges in byte-range requests. Requests that exceed the limit are processed as if there were no byte ranges specified. By default, the number of ranges is not limited. The zero value disables the byte-range support completely.

on |
default: on
 
context: http, server
 

Enables or disables compression of two or more adjacent slashes in a URI into a single slash. Note that compression is essential for the correct matching of prefix string and regular expression locations. Without it, the "//scripts/one.php" request would not match

location /scripts/ {
    ...
}

and might be processed as a static file. So it gets converted to "/scripts/one.php". Turning the compression off can become necessary if a URI contains base64-encoded names, since base64 uses the "/" character internally. However, for security considerations, it is better to avoid turning the compression off. A directive can be specified on the server level in the default server. In this case, its value will apply to all virtual servers listening on the same address and port.

on |
default: on
 
context: http, server, location
 

Enables or disables adding comments to responses for MSIE clients with status greater than 400 to increase the response size to 512 bytes.

on |
default: off
 
context: http, server, location
 

Enables or disables issuing refreshes instead of redirects for MSIE clients.

off
 
max=N [inactive=time]
default: off
 
context: http, server, location
 

Configures a cache that can store:

  • open file descriptors, their sizes and modification times;
  • information on existence of directories;
  • file lookup errors, such as file not found, no read permission, and so on. Caching of errors should be enabled separately by the open_file_cache_errors directive.

The directive has the following parameters:

sets the maximum number of elements in the cache; on cache overflow the least recently used (LRU) elements are removed;
defines a time after which an element is removed from the cache if it has not been accessed during this time; by default, it is 60 seconds;
disables the cache.

Example:

open_file_cache          max=1000 inactive=20s;
open_file_cache_valid    30s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;
on |
default: off
 
context: http, server, location
 

Enables or disables caching of file lookup errors by open_file_cache.

number
default: 1
 
context: http, server, location
 

Sets the minimum number of file accesses during the period configured by the inactive parameter of the open_file_cache directive, required for a file descriptor to remain open in the cache.

time
default: 60s
 
context: http, server, location
 

Sets a time after which open_file_cache elements should be validated.

on |
default: off
 
context: http, server
 

This directive is obsolete. The server_name_in_redirect directive should be used instead.

on |
default: on
 
context: http, server, location
 

Enables or disables specifying the port in redirects issued by nginx. The use of the primary server name in redirects is controlled by the server_name_in_redirect directive.

size
default: 1460
 
context: http, server, location
 

If possible, the transmission of client data will be postponed until nginx has at least size bytes of data to send. The zero value disables postponing data transmission.

size
default: 0
 
context: http, server, location
 

Sets the amount of pre-reading for the kernel when working with file. On Linux, the (0, 0, 0, POSIX_FADV_SEQUENTIAL) system call is used, and so the size parameter is ignored. On FreeBSD, the (O_READAHEAD, size) system call, supported since FreeBSD 9.0-CURRENT, is used. FreeBSD 7 has to be patched.

on |
default: off
 
context: http, server, location
 

Enables or disables doing several redirects using the error_page directive. The number of such redirects is internal limited .

size
default: 4k
 
context: http, server
 

Allows accurate tuning of per-request memory allocations. This directive has minimal impact on performance and should not generally be used.

on |
default: off
 
context: http, server, location
 

Enables or disables resetting timed out connections. The reset is performed as follows. Before closing a socket, the SO_LINGER option is set on it with a timeout value of 0. When the socket is closed, TCP RST is sent to the client, and all memory occupied by this socket is released. This helps avoid keeping an already closed socket with filled buffers in a FIN_WAIT1 state for a long time. It should be noted that timed out keep-alive connections are closed normally.

address ... [valid=time]
default:
 
context: http, server, location
 

Configures name servers used to resolve names of upstream servers into addresses, for example:

resolver 127.0.0.1 [::1]:5353;

An address can be specified as a domain name or IP address, and an optional port (1.3.1, 1.2.2). If port is not specified, the port 53 is used. Name servers are queried in a round-robin fashion. Before version 1.1.7, only a single name server could be configured. Specifying name servers using IPv6 addresses is supported starting from versions 1.3.1 and 1.2.2.By default, nginx caches answers using the TTL value of a response. An optional valid parameter allows overriding it:

resolver 127.0.0.1 [::1]:5353 valid=30s;

Before version 1.1.9, tuning of caching time was not possible, and nginx always cached answers for the duration of 5 minutes.

time
default: 30s
 
context: http, server, location
 

Sets a timeout for name resolution, for example:

resolver_timeout 5s;
path
default: html
 
context: http, server, location, if in location
 

Sets the root directory for requests. For example, with the following configuration

location /i/ {
    root /data/w3;
}

The /data/w3/i/top.gif file will be sent in response to the "/i/top.gif" request. The path value can contain variables, except $document_root and $realpath_root. A path to the file is constructed by merely adding a URI to the value of the root directive. If a URI has to be modified, the alias directive should be used.

all |
default: all
 
context: http, server, location
 

Allows access if all (all) or at least one (any) of the Module ngx_http_access_module, Module ngx_http_auth_basic_module or Module ngx_http_auth_request_module modules allow access. Example:

location / {
    satisfy any;
    allow 192.168.1.0/32;
    deny  all;
    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}
on |
default: off
 
context: http, server, location
 

This directive has been replaced by the any parameter of the satisfy directive.

size
default: 0
 
context: http, server, location
 

If the directive is set to a non-zero value, nginx will try to minimize the number of send operations on client sockets by using either NOTE_LOWAT flag of the kqueue method or the SO_SNDLOWAT socket option. In both cases the specified size is used. This directive is ignored on Linux, Solaris, and Windows.

time
default: 60s
 
context: http, server, location
 

Sets a timeout for transmitting a response to the client. A timeout is set only between two successive write operations, not for the transmission of the whole response. If a client does not receive anything within this time, a connection is closed.

on |
default: off
 
context: http, server, location, if in location
 

Enables or disables the use of ().

size
default: 0
 
context: http, server, location
 

When set to a non-zero value, limits the amount of data that can be transferred in a single () call. Without the limit, one fast connection may seize the worker process entirely.

{...}
default:
 
context: http
 

Sets configuration for a virtual server. There is no clear separation between IP-based (based on the IP address) and name-based (based on the Host request header field) virtual servers. Instead, the listen directives describe all addresses and ports that should accept connections for the server, and the server_name directive lists all server names.

name ...
default: ""
 
context: server
 

Sets names of a virtual server, for example:

server {
    server_name example.com www.example.com;
}

The first name becomes the primary server name. Server names can include an asterisk (*) replacing the first or last part of a name:

server {
    server_name example.com *.example.com www.example.*;
}

Such names are called wildcard names. The first two of the names mentioned above can be combined in one:

server {
    server_name .example.com;
}

It is also possible to use regular expressions in server names, preceding the name with a tilde (~):

server {
    server_name www.example.com ~^www\d+\.example\.com$;
}

Regular expressions can contain captures (0.7.40) that can later be used in other directives:

server {
    server_name ~^(www\.)?(.+)$;
    location / {
        root /sites/$2;
    }
}
server {
    server_name _;
    location / {
        root /sites/default;
    }
}

Named captures in regular expressions create variables (0.8.25) that can later be used in other directives:

server {
    server_name ~^(www\.)?(?<domain>.+)$;
    location / {
        root /sites/$domain;
    }
}
server {
    server_name _;
    location / {
        root /sites/default;
    }
}

If the directive's parameter is set to $hostname (0.9.4), the machine's hostname is inserted. It is also possible to specify an empty server name (0.7.11):

server {
    server_name www.example.com "";
}

It allows this server to process requests without the Host header field - instead of the default server - for the given address:port pair. This is the default setting. Before 0.8.48, the machine's hostname was used by default. During searching for a virtual server by name, if the name matches more than one of the specified variants, (e.g. both a wildcard name and regular expression match), the first matching variant will be chosen, in the following order of priority:

  • the exact name
  • the longest wildcard name starting with an asterisk, e.g. *.example.com
  • the longest wildcard name ending with an asterisk, e.g. mail.*
  • the first matching regular expression (in order of appearance in the configuration file)
Detailed description of server names is provided in a separate document.
on |
default: off
 
context: http, server, location
 

Enables or disables the use of the primary server name, specified by the server_name directive, in redirects issued by nginx. When the use of the primary server name is disabled, the name from the Host request header field is used. If this field is not present, the IP address of the server is used. The use of a port in redirects is controlled by the port_in_redirect directive.

size
default: 32 | 64 | 128
 
context: http
 

Sets the bucket size for the server names hash tables. The default value depends on the size of the processor's cache line. The details of setting up hash tables are provided in a separate document.

size
default: 512
 
context: http
 

Sets the maximum size of the server names hash tables. The details of setting up hash tables are provided in a separate document.

on |
default: on
 
context: http, server, location
 

Enables or disables emitting nginx version in error messages and in the Server response header field.

on |
default: on
 
context: http, server, location
 

Enables or disables the use of the TCP_NODELAY option. The option is enabled only when a connection is transitioned into the keep-alive state.

on |
default: off
 
context: http, server, location
 

Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or the TCP_CORK socket option on Linux. The options are enabled only when sendfile is used. Enabling the option allows

  • sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.*;
  • sending a file in full packets.
file ... uri
 
file ... =code
default:
 
context: server, location
 

Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory's existence by specifying a slash at the end of a name, e.g. "$uri/". If none of the files were found, an internal redirect to the uri specified in the last parameter is made. For example:

location /images/ {
    try_files $uri /images/default.gif;
}
location = /images/default.gif {
    expires 30s;
}

The last parameter can also point to a named location, as shown in examples below. Starting from version 0.7.51, the last parameter can also be a code:

location / {
    try_files $uri $uri/index.html $uri.html =404;
}

Example in proxying Mongrel:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}
location @mongrel {
    proxy_pass http://mongrel;
}

Example for Drupal/FastCGI:

location / {
    try_files $uri $uri/ @drupal;
}
location ~ \.php$ {
    try_files $uri @drupal;
    fastcgi_pass ...;
    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
    fastcgi_param QUERY_STRING    $args;
    ... other fastcgi_param's
}
location @drupal {
    fastcgi_pass ...;
    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    fastcgi_param SCRIPT_NAME     /index.php;
    fastcgi_param QUERY_STRING    q=$uri&$args;
    ... other fastcgi_param's
}

In the following example,

location / {
    try_files $uri $uri/ @drupal;
}

the try_files directive is equivalent to

location / {
    error_page 404 = @drupal;
    log_not_found off;
}

And here,

location ~ \.php$ {
    try_files $uri @drupal;
    fastcgi_pass ...;
    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ...
}

try_files checks the existence of the PHP file before passing the request to the FastCGI server. Example for Wordpress and Joomla:

location / {
    try_files $uri $uri/ @wordpress;
}
location ~ \.php$ {
    try_files $uri @wordpress;
    fastcgi_pass ...;
    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ... other fastcgi_param's
}
location @wordpress {
    fastcgi_pass ...;
    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    ... other fastcgi_param's
}
{...}
default:
    text/html  html;
    image/gif  gif;
    image/jpeg jpg;
context: http, server, location
 

Maps file name extensions to MIME types of responses. Extensions are case-insensitive. Several extensions can be mapped to one type, for example:

types {
    application/octet-stream bin exe dll;
    application/octet-stream deb;
    application/octet-stream dmg;
}

A sufficiently full mapping table is distributed with nginx in the conf/mime.types file. To make a particular location emit the application/octet-stream MIME type for all requests, the following configuration can be used:

location /download/ {
    types        { }
    default_type application/octet-stream;
}
size
default: 32 | 64 | 128
 
context: http, server, location
 

Sets the bucket size for the types hash tables. The default value depends on the size of the processor's cache line. The details of setting up hash tables are provided in a separate document.

size
default: 1024
 
context: http, server, location
 

Sets the maximum size of the types hash tables. The details of setting up hash tables are provided in a separate document.

on |
default: off
 
context: http, server
 

Enables or disables the use of underscores in client request header fields. When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive. A directive can be specified on the server level in a default server. In this case, its value will apply to all virtual servers listening on the same address and port.

size
default: 64
 
context: http
 

Sets the bucket size for the variables hash table. The details of setting up hash tables are provided in a separate document.

size
default: 512
 
context: http
 

Sets the maximum size of the variables hash table. The details of setting up hash tables are provided in a separate document.

The Module ngx_http_core_module module supports embedded variables with names matching the Apache Server variables. First of all, these are variables representing client request header fields, such as $http_user_agent, $http_cookie, and so on. Also there are other variables:

$arg_name
argument name in the request line
$args
arguments in the request line
$binary_remote_addr
client address in a binary form, value's length is always 4 bytes
$body_bytes_sent
number of bytes sent to a client, not counting the response header; this variable is compatible with the "%B" parameter of the mod_log_config Apache module
$bytes_sent
number of bytes sent to a client (1.3.8, 1.2.5)
$connection
connection serial number (1.3.8, 1.2.5)
$connection_requests
current number of requests made through a connection (1.3.8, 1.2.5)
$content_length
Content-Length request header field
$content_type
Content-Type request header field
$cookie_name
the name cookie
$document_root
or alias directive's value for the current request
$document_uri
same as $uri
$host
in this order of precedence: host name from the request line, or host name from the Host request header field, or the server name matching a request
$hostname
host name
$http_name
arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores
$https
"on" if connection operates in SSL mode, or an empty string otherwise
$is_args
"?" if a request line has arguments, or an empty string otherwise
$limit_rate
setting this variable enables response rate limiting; see limit_rate
$msec
current time in seconds with the milliseconds resolution (1.3.9, 1.2.6)
$nginx_version
nginx version
$pid
PID of the worker process
$pipe
"p" if request was pipelined, "." otherwise (1.3.12, 1.2.7)
$query_string
same as $args
$realpath_root
an absolute pathname corresponding to the root or alias directive's value for the current request, with all symbolic links resolved to real paths
$remote_addr
client address
$remote_port
client port
$remote_user
user name supplied with the Basic authentication
$request
full original request line
$request_body
request body

The variable's value is made available in locations processed by the proxy_pass and fastcgi_pass directives.

$request_body_file
name of a temporary file with the request body

At the end of processing, the file needs to be removed. To always write the request body to a file, client_body_in_file_only needs to be enabled. When the name of a temporary file is passed in a proxied request or in a request to a FastCGI server, passing the request body should be disabled by the proxy_pass_request_body off and fastcgi_pass_request_body off directives, respectively.

$request_completion
"OK" if a request has completed, or an empty string otherwise
$request_filename
file path for the current request, based on the root or alias directives, and the request URI
$request_length
request length (including request line, header, and request body) (1.3.12, 1.2.7)
$request_method
request method, usually GET or POST
$request_time
request processing time in seconds with a milliseconds resolution (1.3.9, 1.2.6); time elapsed since the first bytes were read from the client
$request_uri
full original request URI (with arguments)
$scheme
request scheme, "http" or "https"
$sent_http_name
arbitrary response header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores
$server_addr
an address of the server which accepted a request

Computing a value of this variable usually requires one system call. To avoid a system call, the listen directives must specify addresses and use the bind parameter.

$server_name
name of the server which accepted a request
$server_port
port of the server which accepted a request
$server_protocol
request protocol, usually "HTTP/1.0" or "HTTP/1.1"
$status
response status (1.3.2, 1.2.2)
$tcpinfo_rtt,
$tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space information about the client TCP connection; available on systems that support the TCP_INFO socket option
$time_iso8601
local time in the ISO 8601 standard format (1.3.12, 1.2.7)
$time_local
local time in the Common Log Format (1.3.12, 1.2.7)
$uri
current URI in request, normalized

The value of $uri may change during request processing, e.g. when doing internal redirects, or when using index files.

address | CIDR | |
default:
 
context: http, server, location, limit_except
 

Allows access for the specified network or address. If the special value unix: is specified (1.5.1), allows access for all UNIX-domain sockets.

address | CIDR | |
default:
 
context: http, server, location, limit_except
 

Denies access for the specified network or address. If the special value unix: is specified (1.5.1), denies access for all UNIX-domain sockets.

This module is not enabled on OpenBSD.

uri
default:
 
context: http, server, location
 

Adds the text returned as a result of processing a given subrequest before the response body. An empty string () as a parameter cancels addition inherited from the previous configuration level.

uri
default:
 
context: http, server, location
 

Adds the text returned as a result of processing a given subrequest after the response body. An empty string () as a parameter cancels addition inherited from the previous configuration level.

mime-type ...
default: text/html
 
context: http, server, location
 

Allows adding text in responses with the specified MIME types, in addition to "text/html". The special value "*" matches any MIME type (0.8.29).

string |
default: off
 
context: http, server, location, limit_except
 

Enables validation of user name and password using the HTTP Basic Authentication protocol. The specified parameter is used as a realm. Parameter value can contain variables (1.3.10, 1.2.7). The special value off allows cancelling the effect of the auth_basic directive inherited from the previous configuration level.

file
default:
 
context: http, server, location, limit_except
 

Specifies a file that keeps user names and passwords, in the following format:

# comment
name1:password1
name2:password2:comment
name3:password3

The following password types are supported:

  • encrypted with the () function; can be generated using the htpasswd utility from the Apache HTTP Server distribution or the openssl passwd command;
  • hashed with the Apache variant of the MD5-based password algorithm (apr1); can be generated with the same tools;
  • specified by the {scheme} data syntax (1.0.3+) as described in RFC 2307; currently implemented schemes include PLAIN (an example one, should not be used), SHA (1.3.13) (plain SHA-1 hashing, should not be used) and SSHA (salted SHA-1 hashing, used by some software packages, notably OpenLDAP and Dovecot). Support for SHA scheme was added only to aid in migration from other web servers. It should not be used for new passwords, since unsalted SHA-1 hashing that it employs is vulnerable to rainbow table attacks.

This module is not enabled on OpenBSD.

uri |
default: off
 
context: http, server, location
 

Enables authorization based on the result of a subrequest and sets the URI to which the subrequest will be sent.

variable value
default:
 
context: http, server, location
 

Sets the request variable to the given value after the authorization request completes. The value may contain variables from the authorization request, such as $upstream_http_*.

on |
default: off
 
context: http, server, location
 

Enables or disables the directory listing output.

on |
default: on
 
context: http, server, location
 

Specifies whether exact file sizes should be output in the directory listing, or rather rounded to kilobytes, megabytes, and gigabytes.

on |
default: off
 
context: http, server, location
 

Specifies whether times in the directory listing should be output in the local time zone or UTC.

string ...
default:
 
context: http, server, location
 

If any of the specified substrings is found in the User-Agent request header field, the browser will be considered ancient. The special string netscape4 corresponds to the regular expression "^Mozilla/[1-4]".

string
default: 1
 
context: http, server, location
 

Sets a value for the $ancient_browser variables.

browser version
 
unlisted
default:
 
context: http, server, location
 

Specifies a version starting from which a browser is considered modern. A browser can be any one of the following: msie, gecko (browsers based on Mozilla), opera, safari, or konqueror. Versions can be specified in the following formats: X, X.X, X.X.X, or X.X.X.X. The maximum values for each of the format are 4000, 4000.99, 4000.99.99, and 4000.99.99.99, respectively. The special value unlisted specifies to consider a browser as modern if it was not listed by the modern_browser and ancient_browser directives. Otherwise such a browser is considered ancient. If a request does not provide the User-Agent field in the header, the browser is treated as not being listed.

string
default: 1
 
context: http, server, location
 

Sets a value for the $modern_browser variables.

charset |
default: off
 
context: http, server, location, if in location
 

Adds the specified charset to the Content-Type response header field. If this charset is different from the charset specified in the source_charset directive, a conversion is performed. The parameter off cancels the addition of charset to the Content-Type response header field. A charset can be defined with a variable:

charset $charset;

In such a case, all possible values of a variable need to be present in the configuration at least once in the form of the charset_map, charset, or source_charset directives. For utf-8, windows-1251, and koi8-r charsets, it is sufficient to include the files conf/koi-win, conf/koi-utf, and conf/win-utf into configuration. For other charsets, simply making a fictitious conversion table works, for example:

charset_map iso-8859-5 _ { }

In addition, a charset can be set in the X-Accel-Charset response header field. This capability can be disabled using the proxy_ignore_headers and fastcgi_ignore_headers directives.

charset1 charset2 {...}
default:
 
context: http
 

Describes the conversion table from one charset to another. A reverse conversion table is built using the same data. Character codes are given in hexadecimal. Missing characters in the range 80-FF are replaced with ""?. When converting from UTF-8, characters missing in a one-byte charset are replaced with "&#XXXX;". Example:

charset_map koi8-r windows-1251 {
    C0 FE ; # small yu
    C1 E0 ; # small a
    C2 E1 ; # small b
    C3 F6 ; # small ts
    ...
}

When describing a conversion table to UTF-8, codes for the UTF-8 charset should be given in the second column, for example:

charset_map koi8-r utf-8 {
    C0 D18E ; # small yu
    C1 D0B0 ; # small a
    C2 D0B1 ; # small b
    C3 D186 ; # small ts
    ...
}

Full conversion tables from koi8-r to windows-1251, and from koi8-r and windows-1251 to utf-8 are provided in the distribution files conf/koi-win, conf/koi-utf, and conf/win-utf.

mime-type ...
default: text/html text/xml text/plain text/vnd.wap.wml
application/javascript application/rss+xml
context: http, server, location
 

Enables module processing in responses with the specified MIME types in addition to text/html. The special value "*" matches any MIME type (0.8.29). Until version 1.5.4, application/x-javascript was used as the default MIME type instead of application/javascript .

on |
default: off
 
context: http, server, location, if in location
 

Determines whether a conversion should be performed for answers received from a proxied or FastCGI server when the answers already carry a charset in the Content-Type response header field. If conversion is enabled, a charset specified in the received response is used as a source charset. It should be noted that if a response is received in a subrequest then the conversion from the response charset to the main request charset is always performed, regardless of the override_charset directive setting.

charset
default:
 
context: http, server, location, if in location
 

Defines the source charset of a response. If this charset is different from the charset specified in the charset directive, a conversion is performed.

This module is not enabled on OpenBSD.

users:permissions ...
default: user:rw
 
context: http, server, location
 

Sets access permissions for newly created files and directories, e.g.:

dav_access user:rw group:rw all:r;

If any group or all access permissions are specified then user permissions may be omitted:

dav_access group:rw all:r;
off | method ...
default: off
 
context: http, server, location
 

Allows the specified HTTP and WebDAV methods. The parameter off denies all methods processed by this module. The following methods are supported: PUT, DELETE, MKCOL, COPY, and MOVE. A file uploaded with the PUT method is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the persistent store can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both saved files and a directory holding temporary files, set by the client_body_temp_path directive, are put on the same file system. When creating a file with the PUT method, it is possible to specify the modification date by passing it in the Date header field.

on |
default: off
 
context: http, server, location
 

The WebDAV specification only allows creating files in already existing directories. This directive allows creating all needed intermediate directories.

number
default: 0
 
context: http, server, location
 

Allows the DELETE method to remove files provided that the number of elements in a request path is not less than the specified number. For example, the directive

min_delete_depth 4;

allows removing files on requests

/users/00/00/name
/users/00/00/name/pic.jpg
/users/00/00/page.html

and denies the removal of

/users/00/00

default:
 
context: location
 

Turns on module processing in a surrounding location.

This module is only available in the commercial version of nginx.

default:
 
context: location
 

Turns on module processing in the surrounding location.

size
default: 512k
 
context: http, server, location
 

Sets the size of a memory buffer used for reading the .f4x index file.

address |
default:
 
context: http, server, location
 

Makes outgoing connections to a FastCGI server originate from the specified local IP address. Parameter value can contain variables (1.3.12). The special value off (1.3.12) cancels the effect of the fastcgi_bind directive inherited from the previous configuration level, which allows the system to auto-assign the local IP address.

size
default: 4k | 8k
 
context: http, server, location
 

Sets the size of the buffer used for reading the first part of a response received from the FastCGI server. This part usually contains a small response header. By default, the buffer size is equal to the size of one buffer set by the fastcgi_buffers directive. It can be made smaller however.

on |
default: on
 
context: http, server, location
 

Enables or disables buffering of responses from the FastCGI server. When buffering is enabled, nginx receives a response from the FastCGI server as soon as possible, saving it into the buffers set by the fastcgi_buffer_size and fastcgi_buffers directives. If the whole response does not fit into memory, a part of it can be saved to a fastcgi_temp_path temporary file on the disk. Writing to temporary files is controlled by the fastcgi_max_temp_file_size and fastcgi_temp_file_write_size directives. When buffering is disabled, a response is passed to a client synchronously, immediately as it is received. nginx will not try to read the whole response from the FastCGI server. The maximum size of the data that nginx can receive from the server at a time is set by the fastcgi_buffer_size directive. Buffering can also be enabled or disabled by passing yes or no in the X-Accel-Buffering response header field. This capability can be disabled using the fastcgi_ignore_headers directive.

number size
default: 8 4k | 8k
 
context: http, server, location
 

Sets the number and size of buffers used for reading a response from the FastCGI server, for a single connection. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

size
default: 8k | 16k
 
context: http, server, location
 

When fastcgi_buffering buffering of responses from the FastCGI server is enabled, limits the total size of buffers that can be busy sending a response to the client while the response is not yet fully read. In the mean time, the rest of the buffers can be used for reading a response and, if needed, buffering part of a response to a temporary file. By default, size is limited by the size of two buffers set by the fastcgi_buffer_size and fastcgi_buffers directives.

zone |
default: off
 
context: http, server, location
 

Defines a shared memory zone used for caching. The same zone can be used in several places. The off parameter disables caching inherited from the previous configuration level.

string ...
default:
 
context: http, server, location
 

Defines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to 0 then the response will not be taken from the cache:

fastcgi_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
fastcgi_cache_bypass $http_pragma    $http_authorization;

Can be used along with the fastcgi_no_cache directive.

string
default:
 
context: http, server, location
 

Defines a key for caching, for example

fastcgi_cache_key localhost:9000$request_uri;
on |
default: off
 
context: http, server, location
 

When enabled, only one request at a time will be allowed to populate a new cache element identified according to the fastcgi_cache_key directive by passing a request to a FastCGI server. Other requests of the same cache element will either wait for a response to appear in the cache or the cache lock for this element to be released, up to the time set by the fastcgi_cache_lock_timeout directive.

time
default: 5s
 
context: http, server, location
 

Sets a timeout for fastcgi_cache_lock.

GET | | ...
default: GET HEAD
 
context: http, server, location
 

If the client request method is listed in this directive then the response will be cached. GET and HEAD methods are always added to the list, though it is recommended to specify them explicitly. See also the fastcgi_no_cache directive.

number
default: 1
 
context: http, server, location
 

Sets the number of requests after which the response will be cached.

path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time]
default:
 
context: http
 

Sets the path and other parameters of a cache. Cache data are stored in files. Both the key and file name in a cache are a result of applying the MD5 function to the proxied URL. The levels parameter defines hierarchy levels of a cache. For example, in the following configuration

fastcgi_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;

file names in a cache will look like this:

/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c

A cached response is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the cache can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both cache and a directory holding temporary files, set by the fastcgi_temp_path directive, are put on the same file system. In addition, all active keys and information about data are stored in a shared memory zone, whose name and size are configured by the keys_zone parameter. Cached data that are not accessed during the time specified by the inactive parameter get removed from the cache regardless of their freshness. By default, inactive is set to 10 minutes. The special cache manager process monitors the maximum cache size set by the max_size parameter. When this size is exceeded, it removes the least recently used data. A minute after the start the special cache loader process is activated. It loads information about previously cached data stored on file system into a cache zone. The loading is done in iterations. During one iteration no more than loader_files items are loaded (by default, 100). Besides, the duration of one iteration is limited by the loader_threshold parameter (by default, 200 milliseconds). Between iterations, a pause configured by the loader_sleep parameter (by default, 50 milliseconds) is made.

error | | | | | | | | ...
default: off
 
context: http, server, location
 

Determines in which cases a stale cached response can be used when an error occurs during communication with the FastCGI server. The directive's parameters match the parameters of the fastcgi_next_upstream directive. Additionally, the updating parameter permits using a stale cached response if it is currently being updated. This allows minimizing the number of accesses to FastCGI servers when updating cached data. To minimize the number of accesses to FastCGI servers when populating a new cache element, the fastcgi_cache_lock directive can be used.

[code ...] time
default:
 
context: http, server, location
 

Sets caching time for different response codes. For example, the following directives

fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404      1m;

set 10 minutes of caching for responses with codes 200 and 302 and 1 minute for responses with code 404. If only caching time is specified

fastcgi_cache_valid 5m;

then only 200, 301, and 302 responses are cached. In addition, the any parameter can be specified to cache any responses:

fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 301      1h;
fastcgi_cache_valid any      1m;

Parameters of caching can also be set directly in the response header. This has higher priority than setting of caching time using the directive. The X-Accel-Expires header field sets caching time of a response in seconds. The zero value disables caching for a response. If a value starts with the "@" prefix, it sets an absolute time in seconds since Epoch, up to which the response may be cached. If header does not include the X-Accel-Expires field, parameters of caching may be set in the header fields Expires or Cache-Control . If a header includes the Set-Cookie field, such a response will not be cached. Processing of one or more of these response header fields can be disabled using the fastcgi_ignore_headers directive.

string
default:
 
context: http, server, location
 

Sets a string to search for in the error stream of a response received from a FastCGI server. If the string is found then it is considered that the FastCGI server has returned an fastcgi_next_upstream invalid response. This allows handling application errors in nginx, for example:

location /php {
    fastcgi_pass backend:9000;
    ...
    fastcgi_catch_stderr "PHP Fatal error";
    fastcgi_next_upstream error timeout invalid_header;
}
time
default: 60s
 
context: http, server, location
 

Defines a timeout for establishing a connection with a FastCGI server. It should be noted that this timeout cannot usually exceed 75 seconds.

field
default:
 
context: http, server, location
 

By default, nginx does not pass the header fields Status and X-Accel-... from the response of a FastCGI server to a client. The fastcgi_hide_header directive sets additional fields that will not be passed. If, on the contrary, the passing of fields needs to be permitted, the fastcgi_pass_header directive can be used.

on |
default: off
 
context: http, server, location
 

Determines whether the connection with a FastCGI server should be closed when a client closes a connection without waiting for a response.

field ...
default:
 
context: http, server, location
 

Disables processing of certain response header fields from the FastCGI server. The following fields can be ignored: X-Accel-Redirect, X-Accel-Expires, X-Accel-Limit-Rate (1.1.6), X-Accel-Buffering (1.1.6), X-Accel-Charset (1.1.6), Expires, Cache-Control and Set-Cookie (0.8.44). If not disabled, processing of these header fields has the following effect:

  • X-Accel-Expires, Expires, Cache-Control and Set-Cookie set the parameters of response fastcgi_cache_valid caching;
  • X-Accel-Redirect performs an internal redirect to the specified URI;
  • X-Accel-Limit-Rate sets the limit_rate rate limit for transmission of a response to a client;
  • X-Accel-Buffering enables or disables fastcgi_buffering buffering of a response;
  • X-Accel-Charset sets the desired charset of a response.
name
default:
 
context: http, server, location
 

Sets a file name that will be appended after a URI that ends with a slash, in the value of the $fastcgi_script_name variable. For example, with these settings

fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;

and the "/page.php" request, the SCRIPT_FILENAME parameter will be equal to /home/www/scripts/php/page.php, and with the "/" request it will be equal to /home/www/scripts/php/index.php.

on |
default: off
 
context: http, server, location
 

Determines whether FastCGI server responses with codes greater than or equal to 300 should be passed to a client or be redirected to nginx for processing with the error_page directive.

on |
default: off
 
context: http, server, location
 

By default, a FastCGI server will close a connection right after sending the response. However, when this directive is set to the value on, nginx will instruct a FastCGI server to keep connections open. This is necessary, in particular, for keepalive connections to FastCGI servers to function.

size
default: 1024m
 
context: http, server, location
 

When buffering of responses from the FastCGI server is enabled, and the whole response does not fit into the memory buffers set by the fastcgi_buffer_size and fastcgi_buffers directives, a part of the response can be saved to a temporary file. This directive sets the maximum size of a temporary file. The size of data written to a temporary file at a time is set by the fastcgi_temp_file_write_size directive. The zero value disables buffering of responses to temporary files.

error | | | | | | | ...
default: error timeout
 
context: http, server, location
 

Specifies in which cases a request should be passed to the next server:

an error occurred while establishing a connection with the server, passing a request to it, or reading the response header;
a timeout has occurred while establishing a connection with the server, passing a request to it, or reading the response header;
a server returned an empty or invalid response;
a server returned a response with the code 500;
a server returned a response with the code 503;
a server returned a response with the code 403;
a server returned a response with the code 404;
disables passing a request to the next server.

One should bear in mind that passing a request to the next server is only possible if nothing has been sent to a client yet. That is, if an error or timeout occurs in the middle of the transferring of a response, fixing this is impossible. The directive also defines what is considered an unsuccessful attempt of communication with a server. The cases of error, timeout and invalid_header are always considered unsuccessful attempts, even if they are not specified in the directive. The cases of http_500 and http_503 are considered unsuccessful attempts only if they are specified in the directive. The cases of http_403 and http_404 are never considered unsuccessful attempts.

string ...
default:
 
context: http, server, location
 

Defines conditions under which the response will not be saved to a cache. If at least one value of the string parameters is not empty and is not equal to 0 then the response will not be saved:

fastcgi_no_cache $cookie_nocache $arg_nocache$arg_comment;
fastcgi_no_cache $http_pragma    $http_authorization;

Can be used along with the fastcgi_cache_bypass directive.

parameter value [if_not_empty]
default:
 
context: http, server, location
 

Sets a parameter that should be passed to the FastCGI server. A value can contain text, variables, and their combination. These directives are inherited from the previous level if and only if there are no fastcgi_param directives defined on the current level. The following example shows the minimum required settings for PHP:

fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
fastcgi_param QUERY_STRING    $query_string;

The SCRIPT_FILENAME parameter is used in PHP for determining the script name, and the QUERY_STRING parameter is used to pass request parameters. For scripts that process POST requests, the following three parameters are also required:

fastcgi_param REQUEST_METHOD  $request_method;
fastcgi_param CONTENT_TYPE    $content_type;
fastcgi_param CONTENT_LENGTH  $content_length;

If PHP was built with the --enable-force-cgi-redirect configuration parameter, the REDIRECT_STATUS parameter should also be passed with the value 200:

fastcgi_param REDIRECT_STATUS 200;

If a directive is specified with if_not_empty (1.1.11) then such a parameter will not be passed to the server until its value is not empty:

fastcgi_param HTTPS           $https if_not_empty;
address
default:
 
context: location, if in location
 

Sets the address of a FastCGI server. The address can be specified as a domain name or IP address, and an optional port:

fastcgi_pass localhost:9000;

or as a UNIX-domain socket path:

fastcgi_pass unix:/tmp/fastcgi.socket;

If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a server group.

field
default:
 
context: http, server, location
 

Permits passing fastcgi_hide_header otherwise disabled header fields from a FastCGI server to a client.

time
default: 60s
 
context: http, server, location
 

Defines a timeout for reading a response from the FastCGI server. A timeout is set only between two successive read operations, not for the transmission of the whole response. If a FastCGI server does not transmit anything within this time, a connection is closed.

on |
default: on
 
context: http, server, location
 

Indicates whether the original request body is passed to the FastCGI server. See also the fastcgi_pass_request_headers directive.

on |
default: on
 
context: http, server, location
 

Indicates whether the header fields of the original request are passed to the FastCGI server. See also the fastcgi_pass_request_body directive.

size
default: 0
 
context: http, server, location
 

If the directive is set to a non-zero value, nginx will try to minimize the number of send operations on outgoing connections to a FastCGI server by using either NOTE_LOWAT flag of the kqueue method, or the SO_SNDLOWAT socket option, with the specified size. This directive is ignored on Linux, Solaris, and Windows.

time
default: 60s
 
context: http, server, location
 

Sets a timeout for transmitting a request to the FastCGI server. A timeout is set only between two successive write operations, not for the transmission of the whole request. If a FastCGI server does not receive anything within this time, a connection is closed.

regex
default:
 
context: location
 

Defines a regular expression that captures a value for the $fastcgi_path_info variable. A regular expression should have two captures: the first becomes a value of the $fastcgi_script_name variable, the second becomes a value of the $fastcgi_path_info variable. For example, with these settings

location ~ ^(.+\.php)(.*)$ {
    fastcgi_split_path_info       ^(.+\.php)(.*)$;
    fastcgi_param SCRIPT_FILENAME /path/to/php$fastcgi_script_name;
    fastcgi_param PATH_INFO       $fastcgi_path_info;

and the "/show.php/article/0001" request, the SCRIPT_FILENAME parameter will be equal to /path/to/php/show.php, and the PATH_INFO parameter will be equal to /article/0001.

on | | string
default: off
 
context: http, server, location
 

Enables saving of files to a disk. The on parameter saves files with paths corresponding to the directives alias or root. The off parameter disables saving of files. In addition, the file name can be set explicitly using the string with variables:

fastcgi_store /data/www$original_uri;

The modification time of files is set according to the received Last-Modified response header field. A response is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the persistent store can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both saved files and a directory holding temporary files, set by the fastcgi_temp_path directive, are put on the same file system. This directive can be used to create local copies of static unchangeable files, e.g.:

location /images/ {
    root                   /data/www;
    open_file_cache_errors off;
    error_page             404 = /fetch$uri;
}
location /fetch/ {
    internal;
    fastcgi_pass         backend:9000;
    ...
    fastcgi_store        on;
    fastcgi_store_access user:rw group:rw all:r;
    fastcgi_temp_path    /data/temp;
    alias                /data/www/;
}
users:permissions ...
default: user:rw
 
context: http, server, location
 

Sets access permissions for newly created files and directories, e.g.:

fastcgi_store_access user:rw group:rw all:r;

If any group or all access permissions are specified then user permissions may be omitted:

fastcgi_store_access group:rw all:r;
size
default: 8k | 16k
 
context: http, server, location
 

Limits the size of data written to a temporary file at a time, when buffering of responses from the FastCGI server to temporary files is enabled. By default, size is limited by two buffers set by the fastcgi_buffer_size and fastcgi_buffers directives. The maximum size of a temporary file is set by the fastcgi_max_temp_file_size directive.

path [level1 [level2 [level3]]]
default: fastcgi_temp
 
context: http, server, location
 

Defines a directory for storing temporary files with data received from FastCGI servers. Up to three-level subdirectory hierarchy can be used underneath the specified directory. For example, in the following configuration

fastcgi_temp_path /spool/nginx/fastcgi_temp 1 2;

a temporary file might look like this:

/spool/nginx/fastcgi_temp/7/45/00000123457

This module is not enabled on OpenBSD.

default:
 
context: location
 

Turns on module processing in a surrounding location.

[$address] $variable {...}
default:
 
context: http
 

Describes the dependency of values of the specified variable on the client IP address. By default, the address is taken from the $remote_addr variable, but it can also be taken from another variable (0.7.27), for example:

geo $arg_remote_addr $geo {
    ...;
}

Since variables are evaluated only when used, the mere existence of even a large number of declared geo variables does not cause any extra costs for request processing. If the value of a variable does not represent a valid IP address then the 255.255.255.255 address is used. Addresses are specified either as prefixes in CIDR notation (including individual addresses) or as ranges (0.7.23). IPv6 prefixes are supported starting from versions 1.3.10 and 1.2.7. The following special parameters are also supported:

deletes the specified network (0.7.23).
a value set to the variable if the client address does not match any of the specified addresses. When addresses are specified in CIDR notation, 0.0.0.0/0 and ::/0 can be used instead of default. When default is not specified, the default value will be an empty string.
includes a file with addresses and values. There can be several inclusions.
defines trusted addresses (0.8.7, 0.7.63). When a request comes from a trusted address, an address from the X-Forwarded-For request header field will be used instead. In contrast to the regular addresses, trusted addresses are checked sequentially. Trusted IPv6 addresses are supported starting from versions 1.3.0 and 1.2.1.
enables recursive address search (1.3.0, 1.2.1). If recursive search is disabled then instead of the original client address that matches one of the trusted addresses, the last address sent in X-Forwarded-For will be used. If recursive search is enabled then instead of the original client address that matches one of the trusted addresses, the last non-trusted address sent in X-Forwarded-For will be used.
indicates that addresses are specified as ranges (0.7.23). This parameter should be the first. To speed up loading of a geo base, addresses should be put in ascending order.

Example:

geo $country {
    default        ZZ;
    include        conf/geo.conf;
    delete         127.0.0.0/16;
    proxy          192.168.100.0/24;
    proxy          2001:0db8::/32;
    127.0.0.0/24   US;
    127.0.0.1/32   RU;
    10.1.0.0/16    RU;
    192.168.1.0/24 UK;
}

The conf/geo.conf file could contain the following lines:

10.2.0.0/16    RU;
192.168.2.0/24 RU;

A value of the most specific match is used. For example, for the 127.0.0.1 address the value RU will be chosen, not US . Example with ranges:

geo $country {
    ranges;
    default                   ZZ;
    127.0.0.0-127.0.0.0       US;
    127.0.0.1-127.0.0.1       RU;
    127.0.0.1-127.0.0.255     US;
    10.1.0.0-10.1.255.255     RU;
    192.168.1.0-192.168.1.255 UK;
}

This module is not enabled on OpenBSD.

file
default:
 
context: http
 

Specifies a database used to determine the country depending on the client IP address. The following variables are available when using this database:

$geoip_country_code
two-letter country code, for example, RU, US.
$geoip_country_code3
three-letter country code, for example, RUS, USA.
$geoip_country_name
country name, for example, Russian Federation, United States.
file
default:
 
context: http
 

Specifies a database used to determine the country, region, and city depending on the client IP address. The following variables are available when using this database:

$geoip_area_code
telephone area code (US only). This variable may contain outdated information since the corresponding database field is deprecated.
$geoip_city_continent_code
two-letter continent code, for example, EU, NA.
$geoip_city_country_code
two-letter country code, for example, RU, US.
$geoip_city_country_code3
three-letter country code, for example, RUS, USA.
$geoip_city_country_name
country name, for example, Russian Federation, United States.
$geoip_dma_code
DMA region code in US (also known as metro code), according to the geotargeting in Google AdWords API.
$geoip_latitude
latitude.
$geoip_longitude
longitude.
$geoip_region
two-symbol country region code (region, territory, state, province, federal land and the like), for example, 48, DC.
$geoip_region_name
country region name (region, territory, state, province, federal land and the like), for example, Moscow City, District of Columbia.
$geoip_city
city name, for example, Moscow, Washington.
$geoip_postal_code
postal code.
file
default:
 
context: http
 

Specifies a database used to determine the organization depending on the client IP address. The following variable is available when using this database:

$geoip_org
organization name, for example, The University of Melbourne.
address | CIDR
default:
 
context: http
 

Defines trusted addresses. When a request comes from a trusted address, an address from the X-Forwarded-For request header field will be used instead.

on |
default: off
 
context: http
 

If recursive search is disabled then instead of the original client address that matches one of the trusted addresses, the last address sent in X-Forwarded-For will be used. If recursive search is enabled then instead of the original client address that matches one of the trusted addresses, the last non-trusted address sent in X-Forwarded-For will be used.

This module is not enabled on OpenBSD.

on |
default: off
 
context: http, server, location
 

Enables or disables decompression of gzipped responses for clients that lack gzip support. If enabled, the following directives are also taken into account when determining if clients support gzip: gzip_http_version, gzip_proxied, and gzip_disable. See also the gzip_vary directive.

number size
default: 32 4k | 16 8k
 
context: http, server, location
 

Sets the number and size of buffers used to decompress a response. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

on |
default: off
 
context: http, server, location, if in location
 

Enables or disables gzipping of responses.

number size
default: 32 4k | 16 8k
 
context: http, server, location
 

Sets the number and size of buffers used to compress a response. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform. Until version 0.7.28, four 4K or 8K buffers were used by default.

level
default: 1
 
context: http, server, location
 

Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9.

regex ...
default:
 
context: http, server, location
 

Disables gzipping of responses for requests with User-Agent header fields matching any of the specified regular expressions. The special mask msie6 (0.7.12) corresponds to the regular expression "MSIE[4-6].", but works faster. Starting from version 0.8.11, "MSIE 6.0; ... SV1" is excluded from this mask.

length
default: 20
 
context: http, server, location
 

Sets the minimum length of a response that will be gzipped. The length is determined only from the Content-Length response header field.

1.0 |
default: 1.1
 
context: http, server, location
 

Sets the minimum HTTP version of a request required to compress a response.

off | | | | | | | | ...
default: off
 
context: http, server, location
 

Enables or disables gzipping of responses for proxied requests depending on the request and response. The fact that the response is proxied is determined by the presence of the Via request header field. A directive accepts multiple parameters:

disables compression for all proxied requests, ignoring other parameters;
enables compression if a response header includes the Expires field with a value that disables caching;
enables compression if a response header includes the Cache-Control field with the no-cache parameter;
enables compression if a response header includes the Cache-Control field with the no-store parameter;
enables compression if a response header includes the Cache-Control field with the private parameter;
enables compression if a response header does not include the Last-Modified field;
enables compression if a response header does not include the ETag field;
enables compression if a request header includes the Authorization field;
enables compression for all proxied requests.
mime-type ...
default: text/html
 
context: http, server, location
 

Enables gzipping of responses for the specified MIME types in addition to text/html. The special value "*" matches any MIME type (0.8.29). Responses with the text/html type are always compressed.

on |
default: off
 
context: http, server, location
 

Enables or disables inserting the Vary: Accept-Encoding response header field if the directives gzip, gzip_static, or gunzip are active.

on | |
default: off
 
context: http, server, location
 

Enables (on) or disables (off) checking the existence of precompressed files. The following directives are also taken into account: gzip_http_version, gzip_proxied, gzip_disable, and gzip_vary. With the always value (1.3.6), gzipped file is used in all cases, without checking if the client supports it. It is useful if there are no uncompressed files on the disk anyway or the Module ngx_http_gunzip_module is used. The files can be compressed using the gzip command, or any other compatible one. It is recommended that the modification date and time of original and compressed files be the same.

name value
default:
 
context: http, server, location, if in location
 

Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables.

[modified] time
 
epoch | |
default: off
 
context: http, server, location, if in location
 

Enables or disables adding or modifying the Expires and Cache-Control response header fields provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A parameter can be a positive or negative time. A time in the Expires field is computed as a sum of the current time and time specified in the directive. If the modified parameter is used (0.7.0, 0.6.32) then time is computed as a sum of the file's modification time and time specified in the directive. In addition, it is possible to specify a time of the day using the "@" prefix (0.7.9, 0.6.34):

expires @15h30m;

The epoch parameter corresponds to the absolute time Thu, 01 Jan 1970 00:00:01 GMT. The contents of the Cache-Control field depends on the sign of the specified time:

  • time is negative - Cache-Control: no-cache.
  • time is positive or zero - Cache-Control: max-age=t, where t is a time specified in the directive, in seconds.

The max parameter sets Expires to the value "Thu, 31 Dec 2037 23:55:55 GMT", and Cache-Control to 10 years. The off parameter disables adding or modifying the Expires and Cache-Control response header fields.

This module is only available in the commercial version of nginx.

default:
 
context: location
 

Turns on HLS streaming in the surrounding location.

number size
default: 8 2m
 
context: http, server, location
 

Sets the maximum number and size of buffers that are used for reading and writing data frames.

time
default: 5s
 
context: http, server, location
 

Defines the default fragment length for playlist URIs requested without the len argument.

size
default: 512k
 
context: http, server, location
 

Sets the initial size of the memory buffer used to process MP4 files.

size
default: 10m
 
context: http, server, location
 

During metadata processing, a larger buffer may become necessary. Its size cannot exceed the specified size, or else nginx will return the server error 500 (Internal Server Error), and log the following message:

"/some/movie/file.mp4" mp4 moov atom is too large:
12583268, you may want to increase hls_mp4_max_buffer_size

This module is not enabled on OpenBSD.

off
 
test
 
size
 
rotate 90 | |
 
resize width height
 
crop width height
default: off
 
context: location
 

Sets the type of transformation to perform on images:

turns off module processing in a surrounding location.
ensures that responses are images in either JPEG, GIF, or PNG format. Otherwise, the 415 (Unsupported Media Type) error is returned.
outputs information about images in a JSON format, e.g.:
{ "img" : { "width": 100, "height": 100, "type": "gif" } }

In case of an error, the output is as follows:

{}
90 | |
rotates images counter-clockwise by the specified number of degrees. Parameter value can contain variables. This mode can be used either alone or along with the resize and crop transformations.
width height
proportionally reduces an image to the specified sizes. To reduce by only one dimension, another dimension can be specified as "-". In case of an error, the server will return code 415 (Unsupported Media Type). Parameter values can contain variables. When used along with the rotate parameter, the rotation happens after reduction.
width height
proportionally reduces an image to the larger side size and crops extraneous edges by another side. To reduce by only one dimension, another dimension can be specified as "-". In case of an error, the server will return code 415 (Unsupported Media Type). Parameter values can contain variables. When used along with the rotate parameter, the rotation happens before reduction.
size
default: 1M
 
context: http, server, location
 

Sets the maximum size of the buffer used for reading images. When the size is exceeded the server returns error 415 (Unsupported Media Type).

on |
default: off
 
context: http, server, location
 

If enabled, final images will be interlaced. For JPEG, final images will be in progressive JPEG format.

quality
default: 75
 
context: http, server, location
 

Sets the desired quality of the transformed JPEG images. Acceptable values are in the range from 1 to 100. Lesser values usually imply both lower image quality and less data to transfer. The maximum recommended value is 95. Parameter value can contain variables.

percent
default: 0
 
context: http, server, location
 

Increases sharpness of the final image. The sharpness percentage can exceed 100. The zero value disables sharpening. Parameter value can contain variables.

on |
default: on
 
context: http, server, location
 

Defines whether transparency should be preserved when transforming GIF images or PNG images with colors specified by a palette. The loss of transparency results in images of a better quality. The alpha channel transparency in PNG is always preserved.

file ...
default: index.html
 
context: http, server, location
 

Defines files that will be used as an index. The file name can contain variables. Files are checked in the specified order. The last element of the list can be a file with an absolute path. Example:

index index.$geo.html index.0.html /index.html;

It should be noted that using an index file causes an internal redirect, and the request can be processed in a different location. For example, with the following configuration:

location = / {
    index index.html;
}
location / {
    ...
}

a "/" request will actually be processed in the second location as /index.html.

zone number
default:
 
context: http, server, location
 

Sets the shared memory zone and the maximum allowed number of connections for a given key value. When this limit is exceeded, the server will return the 503 (Service Temporarily Unavailable) error in reply to a request. For example, the directives

limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
    location /download/ {
        limit_conn addr 1;
    }

allow only one connection per an IP address at a time. When several limit_conn directives are specified, any configured limit will apply. For example, the following configuration will limit the number of connections to the server per a client IP and, at the same time, the total number of connections to the virtual host:

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
server {
    ...
    limit_conn perip 10;
    limit_conn perserver 100;
}

These directives are inherited from the previous level if and only if there are no limit_conn directives on the current level.

info | | |
default: error
 
context: http, server, location
 

Sets the desired logging level for cases when the server limits the number of connections.

code
default: 503
 
context: http, server, location
 

Sets the status code to return in response to rejected requests.

$variable zone=name:size
default:
 
context: http
 

Sets parameters for a shared memory zone that will keep states for various keys. In particular, the state includes the current number of connections. The key is any non-empty value of the specified variable (empty values are not accounted). Usage example:

limit_conn_zone $binary_remote_addr zone=addr:10m;

Here, a client IP address serves as a key. Note that instead of $remote_addr, the $binary_remote_addr variable is used here. The $remote_addr variable's size can vary from 7 to 15 bytes. The stored state occupies either 32 or 64 bytes of memory on 32-bit platforms and always 64 bytes on 64-bit platforms. The $binary_remote_addr variable's size is always 4 bytes. The stored state always occupies 32 bytes on 32-bit platforms and 64 bytes on 64-bit platforms. One megabyte zone can keep about 32 thousand 32-byte states or about 16 thousand 64-byte states. If the zone storage is exhausted, the server will return the 503 (Service Temporarily Unavailable) error to all further requests.

name $variable size
default:
 
context: http
 

This directive is made obsolete in version 1.1.8, an equivalent limit_conn_zone directive with a changed syntax should be used instead: limit_conn_zone $variable zone=name:size;

zone=name [burst=number] [nodelay]
default:
 
context: http, server, location
 

Sets the shared memory zone and the maximum burst size of requests. If the requests rate exceeds the rate configured for a zone, their processing is delayed such that requests are processed at a defined rate. Excessive requests are delayed until their number exceeds the maximum burst size in which case the request is terminated with an error 503 (Service Temporarily Unavailable). By default, the maximum burst size is equal to zero. For example, the directives

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
    location /search/ {
        limit_req zone=one burst=5;
    }

allow not more than 1 request per second at an average, with bursts not exceeding 5 requests. If delaying of excessive requests while requests are being limited is not desired, the parameter nodelay should be used:

limit_req zone=one burst=5 nodelay;
info | | |
default: error
 
context: http, server, location
 

Sets the desired logging level for cases when the server refuses to process requests due to rate exceeding, or delays request processing. Logging level for delays is one point less than for refusals; for example, if limit_req_log_level notice is specified, delays are logged with the info level.

code
default: 503
 
context: http, server, location
 

Sets the status code to return in response to rejected requests.

$variable zone=name:size rate=rate
default:
 
context: http
 

Sets parameters for a shared memory zone that will keep states for various keys. In particular, the state stores the current number of excessive requests. The key is any non-empty value of the specified variable (empty values are not accounted). Usage example:

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

Here, the states are kept in a 10 megabyte zone one, and an average request processing rate for this zone cannot exceed 1 request per second. A client IP address serves as a key. Note that instead of $remote_addr, the $binary_remote_addr variable is used here, that allows to decrease the state size down to 64 bytes. One megabyte zone can keep about 16 thousand 64-byte states. If the zone storage is exhausted, the server will return the 503 (Service Temporarily Unavailable) error to all further requests. The rate is specified in requests per second (r/s). If a rate of less than one request per second is desired, it is specified in request per minute (r/m). For example, half-request per second is 30r/m.

path [format [buffer=size [flush=time]]]
 
path format gzip[=level] [buffer=size] [flush=time]
 
syslog:server=address [, parameter=value] [format]
 
off
default: logs/access.log combined
 
context: http, server, location, if in location, limit_except
 

Sets the path, format, and configuration for a buffered log write. Several logs can be specified on the same level. Logging to syslog can be configured by specifying the syslog: prefix in the first parameter. The special value off cancels all access_log directives on the current level. If the format is not specified then the predefined combined format is used. If either the buffer or gzip (1.3.10, 1.2.7) parameter is used, writes to log will be buffered. The buffer size must not exceed the size of an atomic write to a disk file. For FreeBSD this size is unlimited. When buffering is enabled, the data will be written to the file:

  • if the next log line does not fit into the buffer;
  • if the buffered data is older than specified by the flush parameter (1.3.10, 1.2.7);
  • when a worker process is re-opening log files or is shutting down.

If the gzip parameter is used, then the buffered data will be compressed before writing to the file. The compression level can be set between 1 (fastest, less compression) and 9 (slowest, best compression). By default, the buffer size is equal to 64K bytes, and the compression level is set to 1. Since the data is compressed in atomic blocks, the log file can be decompressed or read by zcat at any time. Example:

access_log /path/to/log.gz combined gzip flush=5m;

For gzip compression to work, nginx must be built with the zlib library. The file path can contain variables (0.7.6+), but such logs have some constraints:

  • the user whose credentials are used by worker processes should have permissions to create files in a directory with such logs;
  • buffered writes do not work;
  • the file is opened and closed for each log write. However, since the descriptors of frequently used files can be stored in a open_log_file_cache cache, writing to the old file can continue during the time specified by the open_log_file_cache directive's valid parameter
  • during each log write the existence of the request's root directory is checked, and if it does not exist the log is not created. It is thus a good idea to specify both root and access_log on the same level:
    server {
        root       /spool/vhost/data/$host;
        access_log /spool/vhost/logs/$host;
        ...

The following parameters configure logging to syslog:

=address
Defines the address of a syslog server. The address can be specified as a domain name, IP address, or a UNIX-domain socket path (specified after the unix: prefix). With a domain name or IP address, the port can be specified. If port is not specified, the port 514 is used. If a domain name resolves to several IP addresses, the first resolved address is used.
=string
Sets facility of syslog messages, as defined in RFC 3164. Facility can be one of kern, user, mail, daemon, auth, intern, lpr, news, uucp, clock, authpriv, ftp, ntp, audit, alert, cron, local0 .. local7. Default is local7.
=string
Sets severity of syslog messages, as defined in RFC 3164. Possible values are the same as for the second parameter (level) of the error_log directive. Default is info.
=string
Sets the tag of syslog messages. Default is "nginx".

Example syslog configuration:

access_log syslog:server=192.168.1.1;
access_log syslog:server=unix:/var/log/nginx.sock;
access_log syslog:server=[2001:db8::1]:12345,facility=local7,tag=nginx,severity=info combined;
name string ...
default: combined "..."
 
context: http
 

Specifies log format. The log format can contain common variables, and variables that exist only at the time of a log write:

$bytes_sent
the number of bytes sent to a client
$connection
connection serial number
$connection_requests
the current number of requests made through a connection (1.1.18)
$msec
time in seconds with a milliseconds resolution at the time of the log write
$pipe
"p" if request was pipelined, "." otherwise
$request_length
request length (including request line, header, and request body)
$request_time
request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client
$status
response status
$time_iso8601
local time in the ISO 8601 standard format
$time_local
local time in the Common Log Format

In the modern nginx versions variables $status (1.3.2, 1.2.2), $bytes_sent (1.3.8, 1.2.5), $connection (1.3.8, 1.2.5), $connection_requests (1.3.8, 1.2.5), $msec (1.3.9, 1.2.6), $request_time (1.3.9, 1.2.6), $pipe (1.3.12, 1.2.7), $request_length (1.3.12, 1.2.7), $time_iso8601 (1.3.12, 1.2.7), and $time_local (1.3.12, 1.2.7) are also available as common variables. Header lines sent to a client have the prefix sent_http_, for example, $sent_http_content_range. The configuration always includes the predefined combined format:

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';
max=N [inactive=time] [min_uses=N] [valid=time]
 
off
default: off
 
context: http, server, location
 

Defines a cache that stores the file descriptors of frequently used logs whose names contain variables. The directive has the following parameters:

sets the maximum number of descriptors in a cache; if the cache becomes full the least recently used (LRU) descriptors are closed
sets the time after which the cached descriptor is closed if there were no access during this time; by default, 10 seconds
sets the minimum number of file uses during the time defined by the inactive parameter to let the descriptor stay open in a cache; by default, 1
sets the time after which it should be checked that the file still exists with the same name; by default, 60 seconds
disables caching

Usage example:

open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

string $variable {...}
default:
 
context: http
 

Creates a new variable whose value depends on values of one or more of the source variables specified in the first parameter. Before version 0.9.0 only a single variable could be specified in the first parameter. Since variables are evaluated only when they are used, the mere declaration even of a large number of map variables does not add any extra costs to request processing. Parameters inside the map block specify a mapping between source and resulting values. Source values are specified as strings or regular expressions (0.9.6). A regular expression should either start from the "~" symbol for a case-sensitive matching, or from the "~*" symbols (1.0.4) for case-insensitive matching. A regular expression can contain named and positional captures that can later be used in other directives along with the resulting variable. If a source value matches one of the names of special parameters described below, it should be prefixed with the \ symbol. The resulting value can be a string or another variable (0.9.0). The directive also supports three special parameters:

value
sets the resulting value if the source value matches none of the specified variants. When default is not specified, the default resulting value will be an empty string.
indicates that source values can be hostnames with a prefix or suffix mask:
*.example.com 1;
example.*     1;

The following two records

example.com   1;
*.example.com 1;

can be combined:

 .example.com  1;

This parameter should be specified before the list of values.

file
includes a file with values. There can be several inclusions.

If the source value matches more than one of the specified variants, e.g. both a mask and a regular expression match, the first matching variant will be chosen, in the following order of priority:

  • string value without a mask
  • longest string value with a prefix mask, e.g. "*.example.com"
  • longest string value with a suffix mask, e.g. "mail.*"
  • first matching regular expression (in order of appearance in a configuration file)
  • default value
size
default: 32 | 64 | 128
 
context: http
 

Sets the bucket size for the map variables hash tables. Default value depends on the processor's cache line size. The details of setting up hash tables are provided in a separate document.

size
default: 2048
 
context: http
 

Sets the maximum size of the map variables hash tables. The details of setting up hash tables are provided in a separate document.

address |
default:
 
context: http, server, location
 

Makes outgoing connections to a memcached server originate from the specified local IP address. Parameter value can contain variables (1.3.12). The special value off (1.3.12) cancels the effect of the memcached_bind directive inherited from the previous configuration level, which allows the system to auto-assign the local IP address.

size
default: 4k | 8k
 
context: http, server, location
 

Sets the size of the buffer used for reading a response received from the memcached server. A response is passed to a client synchronously, as soon as it is received.

time
default: 60s
 
context: http, server, location
 

Defines a timeout for establishing a connection with a memcached server. It should be noted that this timeout cannot usually exceed 75 seconds.

flag
default:
 
context: http, server, location
 

Enables the test for the flag presence in the memcached server response and sets the Content-Encoding response header field to gzip if the flag is set.

error | | | | ...
default: error timeout
 
context: http, server, location
 

Specifies in which cases a request should be passed to the next server:

an error occurred while establishing a connection with the server, passing a request to it, or reading the response header;
a timeout has occurred while establishing a connection with the server, passing a request to it, or reading the response header;
a server returned an empty or invalid response;
a response was not found on the server;
disables passing a request to the next server.

One should bear in mind that passing a request to the next server is only possible if nothing has been sent to a client yet. That is, if an error or timeout occurs in the middle of the transferring of a response, fixing this is impossible. The directive also defines what is considered an unsuccessful attempt of communication with a server. The cases of error, timeout and invalid_header are always considered unsuccessful attempts, even if they are not specified in the directive. The case of not_found is never considered an unsuccessful attempt.

address
default:
 
context: location, if in location
 

Sets the memcached server address. The address can be specified as a domain name or an address, and a port:

memcached_pass localhost:11211;

or as a UNIX-domain socket path:

memcached_pass unix:/tmp/memcached.socket;

If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a server group.

time
default: 60s
 
context: http, server, location
 

Defines a timeout for reading a response from the memcached server. A timeout is set only between two successive read operations, not for the transmission of the whole response. If a memcached server does not transmit anything within this time, the connection is closed.

time
default: 60s
 
context: http, server, location
 

Sets a timeout for transmitting a request to the memcached server. A timeout is set only between two successive write operations, not for the transmission of the whole request. If a memcached server does not receive anything within this time, a connection is closed.

This module is not enabled on OpenBSD.

default:
 
context: location
 

Turns on module processing in a surrounding location.

size
default: 512K
 
context: http, server, location
 

Sets the initial size of a memory buffer used for processing MP4 files.

size
default: 10M
 
context: http, server, location
 

During metadata processing, a larger buffer may become necessary. Its size cannot exceed the specified size, or else nginx will return the 500 (Internal Server Error) server error, and log the following message:

"/some/movie/file.mp4" mp4 moov atom is too large:
12583268, you may want to increase mp4_max_buffer_size
on | | factor
default: off
 
context: http, server, location
 

This directive is only available in the commercial version of nginx.

Enables or disables rate limiting based on the average bitrate of the MP4 file served. To calculate the rate, the bitrate is multiplied by the specified factor. The special value on corresponds to the factor of 1.1.

time
default: 1m
 
context: http, server, location
 

This directive is only available in the commercial version of nginx.

Limits the rate after sending the specified amount of media data.

This module is not enabled on OpenBSD.

module::function | 'sub { ... }'
default:
 
context: location, limit_except
 

Sets a Perl handler for the given location.

path
default:
 
context: http
 

Sets an additional path for Perl modules.

module
default:
 
context: http
 

Defines the name of a module that will be loaded during each reconfiguration. Several perl_require directives can be present.

$variable module::function | 'sub { ... }'
default:
 
context: http
 

Installs a Perl handler for the specified variable.

address |
default:
 
context: http, server, location
 

Makes outgoing connections to a proxied server originate from the specified local IP address. Parameter value can contain variables (1.3.12). The special value off (1.3.12) cancels the effect of the proxy_bind directive inherited from the previous configuration level, which allows the system to auto-assign the local IP address.

size
default: 4k | 8k
 
context: http, server, location
 

Sets the size of the buffer used for reading the first part of a response received from the proxied server. This part usually contains a small response header. By default, the buffer size is equal to the size of one buffer set by the proxy_buffers directive. It can be made smaller however.

on |
default: on
 
context: http, server, location
 

Enables or disables buffering of responses from the proxied server. When buffering is enabled, nginx receives a response from the proxied server as soon as possible, saving it into the buffers set by the proxy_buffer_size and proxy_buffers directives. If the whole response does not fit into memory, a part of it can be saved to a proxy_temp_path temporary file on the disk. Writing to temporary files is controlled by the proxy_max_temp_file_size and proxy_temp_file_write_size directives. When buffering is disabled, a response is passed to a client synchronously, immediately as it is received. nginx will not try to read the whole response from the proxied server. The maximum size of the data that nginx can receive from the server at a time is set by the proxy_buffer_size directive. Buffering can also be enabled or disabled by passing yes or no in the X-Accel-Buffering response header field. This capability can be disabled using the proxy_ignore_headers directive.

number size
default: 8 4k | 8k
 
context: http, server, location
 

Sets the number and size of buffers used for reading a response from the proxied server, for a single connection. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

size
default: 8k | 16k
 
context: http, server, location
 

When buffering of responses from the proxied server is enabled, limits the total size of buffers that can be busy sending a response to the client while the response is not yet fully read. In the mean time, the rest of the buffers can be used for reading a response and, if needed, buffering part of a response to a temporary file. By default, size is limited by the size of two buffers set by the proxy_buffer_size and proxy_buffers directives.

zone |
default: off
 
context: http, server, location
 

Defines a shared memory zone used for caching. The same zone can be used in several places. The off parameter disables caching inherited from the previous configuration level.

string ...
default:
 
context: http, server, location
 

Defines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to 0 then the response will not be taken from the cache:

proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
proxy_cache_bypass $http_pragma    $http_authorization;

Can be used along with the proxy_no_cache directive.

string
default: $scheme$proxy_host$request_uri
 
context: http, server, location
 

Defines a key for caching, for example

proxy_cache_key "$host$request_uri $cookie_user";

By default, the directive's value is close to the string

proxy_cache_key $scheme$proxy_host$uri$is_args$args;
on |
default: off
 
context: http, server, location
 

When enabled, only one request at a time will be allowed to populate a new cache element identified according to the proxy_cache_key directive by passing a request to a proxied server. Other requests of the same cache element will either wait for a response to appear in the cache or the cache lock for this element to be released, up to the time set by the proxy_cache_lock_timeout directive.

time
default: 5s
 
context: http, server, location
 

Sets a timeout for proxy_cache_lock.

GET | | ...
default: GET HEAD
 
context: http, server, location
 

If the client request method is listed in this directive then the response will be cached. GET and HEAD methods are always added to the list, though it is recommended to specify them explicitly. See also the proxy_no_cache directive.

number
default: 1
 
context: http, server, location
 

Sets the number of requests after which the response will be cached.

path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time]
default:
 
context: http
 

Sets the path and other parameters of a cache. Cache data are stored in files. Both the key and file name in a cache are a result of applying the MD5 function to the proxied URL. The levels parameter defines hierarchy levels of a cache. For example, in the following configuration

proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;

file names in a cache will look like this:

/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c

A cached response is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the cache can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both cache and a directory holding temporary files, set by the proxy_temp_path directive, are put on the same file system. In addition, all active keys and information about data are stored in a shared memory zone, whose name and size are configured by the keys_zone parameter. Cached data that are not accessed during the time specified by the inactive parameter get removed from the cache regardless of their freshness. By default, inactive is set to 10 minutes. The special cache manager process monitors the maximum cache size set by the max_size parameter. When this size is exceeded, it removes the least recently used data. A minute after the start the special cache loader process is activated. It loads information about previously cached data stored on file system into a cache zone. The loading is done in iterations. During one iteration no more than loader_files items are loaded (by default, 100). Besides, the duration of one iteration is limited by the loader_threshold parameter (by default, 200 milliseconds). Between iterations, a pause configured by the loader_sleep parameter (by default, 50 milliseconds) is made.

error | | | | | | | | | | ...
default: off
 
context: http, server, location
 

Determines in which cases a stale cached response can be used when an error occurs during communication with the proxied server. The directive's parameters match the parameters of the proxy_next_upstream directive. Additionally, the updating parameter permits using a stale cached response if it is currently being updated. This allows minimizing the number of accesses to proxied servers when updating cached data. To minimize the number of accesses to proxied servers when populating a new cache element, the proxy_cache_lock directive can be used.

[code ...] time
default:
 
context: http, server, location
 

Sets caching time for different response codes. For example, the following directives

proxy_cache_valid 200 302 10m;
proxy_cache_valid 404      1m;

set 10 minutes of caching for responses with codes 200 and 302 and 1 minute for responses with code 404. If only caching time is specified

proxy_cache_valid 5m;

then only 200, 301, and 302 responses are cached. In addition, the any parameter can be specified to cache any responses:

proxy_cache_valid 200 302 10m;
proxy_cache_valid 301      1h;
proxy_cache_valid any      1m;

Parameters of caching can also be set directly in the response header. This has higher priority than setting of caching time using the directive. The X-Accel-Expires header field sets caching time of a response in seconds. The zero value disables caching for a response. If a value starts with the "@" prefix, it sets an absolute time in seconds since Epoch, up to which the response may be cached. If header does not include the X-Accel-Expires field, parameters of caching may be set in the header fields Expires or Cache-Control. If a header includes the Set-Cookie field, such a response will not be cached. Processing of one or more of these response header fields can be disabled using the proxy_ignore_headers directive.

time
default: 60s
 
context: http, server, location
 

Defines a timeout for establishing a connection with a proxied server. It should be noted that this timeout cannot usually exceed 75 seconds.

 
default: off
 
context: http, server, location
 

Sets a text that should be changed in the domain attribute of the Set-Cookie header fields of a proxied server response. Suppose a proxied server returned the Set-Cookie header field with the attribute domain=localhost. The directive

proxy_cookie_domain localhost example.org;

will rewrite this attribute to domain=example.org. A dot at the beginning of the domain and replacement strings and the domain attribute is ignored. Matching is case-insensitive. The domain and replacement strings can contain variables:

proxy_cookie_domain www.$host $host;

The directive can also be specified using regular expressions. In this case, domain should start from the "~" symbol. A regular expression can contain named and positional captures, and replacement can reference them:

proxy_cookie_domain ~\.(?P<sl_domain>[-0-9a-z]+\.[a-z]+)$ $sl_domain;

There could be several proxy_cookie_domain directives:

proxy_cookie_domain localhost example.org;
proxy_cookie_domain ~\.([a-z]+\.[a-z]+)$ $1;

The off parameter cancels the effect of all proxy_cookie_domain directives on the current level:

proxy_cookie_domain off;
proxy_cookie_domain localhost example.org;
proxy_cookie_domain www.example.org example.org;
 
default: off
 
context: http, server, location
 

Sets a text that should be changed in the path attribute of the Set-Cookie header fields of a proxied server response. Suppose a proxied server returned the Set-Cookie header field with the attribute path=/two/some/uri/. The directive

proxy_cookie_path /two/ /;

will rewrite this attribute to path=/some/uri/. The path and replacement strings can contain variables:

proxy_cookie_path $uri /some$uri;

The directive can also be specified using regular expressions. In this case, path should either start from the "~" symbol for a case-sensitive matching, or from the "~*" symbols for case-insensitive matching. A regular expression can contain named and positional captures, and replacement can reference them:

proxy_cookie_path ~*^/user/([^/]+) /u/$1;

There could be several proxy_cookie_path directives:

proxy_cookie_path /one/ /;
proxy_cookie_path / /two/;

The off parameter cancels the effect of all proxy_cookie_path directives on the current level:

proxy_cookie_path off;
proxy_cookie_path /two/ /;
proxy_cookie_path ~*^/user/([^/]+) /u/$1;
size
default: 64
 
context: http, server, location
 

Sets the bucket size for hash tables used by the proxy_hide_header and proxy_set_header directives. The details of setting up hash tables are provided in a separate document.

size
default: 512
 
context: http, server, location
 

Sets the maximum size of hash tables used by the proxy_hide_header and proxy_set_header directives. The details of setting up hash tables are provided in a separate document.

field
default:
 
context: http, server, location
 

By default, nginx does not pass the header fields Date, Server, X-Pad and X-Accel-... from the response of a proxied server to a client. The proxy_hide_header directive sets additional fields that will not be passed. If, on the contrary, the passing of fields needs to be permitted, the proxy_pass_header directive can be used.

1.0 |
default: 1.0
 
context: http, server, location
 

Sets the HTTP protocol version for proxying. By default, version 1.0 is used. Version 1.1 is recommended for use with keepalive connections.

on |
default: off
 
context: http, server, location
 

Determines whether the connection with a proxied server should be closed when a client closes a connection without waiting for a response.

field ...
default:
 
context: http, server, location
 

Disables processing of certain response header fields from the proxied server. The following fields can be ignored: X-Accel-Redirect, X-Accel-Expires, X-Accel-Limit-Rate (1.1.6), X-Accel-Buffering (1.1.6), X-Accel-Charset (1.1.6), Expires, Cache-Control and Set-Cookie (0.8.44). If not disabled, processing of these header fields has the following effect:

  • X-Accel-Expires, Expires, Cache-Control, and Set-Cookie set the parameters of response proxy_cache_valid caching;
  • X-Accel-Redirect performs an internal redirect to the specified URI;
  • X-Accel-Limit-Rate sets the limit_rate rate limit for transmission of a response to a client;
  • X-Accel-Buffering enables or disables buffering of a response;
  • X-Accel-Charset sets the desired charset of a response.
on |
default: off
 
context: http, server, location
 

Determines whether proxied responses with codes greater than or equal to 300 should be passed to a client or be redirected to nginx for processing with the error_page directive.

size
default: 1024m
 
context: http, server, location
 

When buffering of responses from the proxied server is enabled, and the whole response does not fit into the memory buffers set by the proxy_buffer_size and proxy_buffers directives, a part of the response can be saved to a temporary file. This directive sets the maximum size of a temporary file. The size of data written to a temporary file at a time is set by the proxy_temp_file_write_size directive. The zero value disables buffering of responses to temporary files.

method
default:
 
context: http, server, location
 

Specifies the HTTP method to use in requests forwarded to the proxied server instead of the method from the client request.

error | | | | | | | | | ...
default: error timeout
 
context: http, server, location
 

Specifies in which cases a request should be passed to the next server:

an error occurred while establishing a connection with the server, passing a request to it, or reading the response header;
a timeout has occurred while establishing a connection with the server, passing a request to it, or reading the response header;
a server returned an empty or invalid response;
a server returned a response with the code 500;
a server returned a response with the code 502;
a server returned a response with the code 503;
a server returned a response with the code 504;
a server returned a response with the code 403;
a server returned a response with the code 404;
disables passing a request to the next server.

One should bear in mind that passing a request to the next server is only possible if nothing has been sent to a client yet. That is, if an error or timeout occurs in the middle of the transferring of a response, fixing this is impossible. The directive also defines what is considered an unsuccessful attempt of communication with a server. The cases of error, timeout and invalid_header are always considered unsuccessful attempts, even if they are not specified in the directive. The cases of http_500, http_502, http_503 and http_504 are considered unsuccessful attempts only if they are specified in the directive. The cases of http_403 and http_404 are never considered unsuccessful attempts.

string ...
default:
 
context: http, server, location
 

Defines conditions under which the response will not be saved to a cache. If at least one value of the string parameters is not empty and is not equal to 0 then the response will not be saved:

proxy_no_cache $cookie_nocache $arg_nocache$arg_comment;
proxy_no_cache $http_pragma    $http_authorization;

Can be used along with the proxy_cache_bypass directive.

URL
default:
 
context: location, if in location, limit_except
 

Sets the protocol and address of a proxied server and an optional URI to which a location should be mapped. As a protocol, http or https can be specified. The address can be specified as a domain name or IP address, and an optional port:

proxy_pass http://localhost:8000/uri/;

or as a UNIX-domain socket path specified after the word unix and enclosed in colons:

proxy_pass http://unix:/tmp/backend.socket:/uri/;

If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a server group. A request URI is passed to the server as follows:

  • If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a location normalized request URI matching the location is replaced by a URI specified in the directive:
    location /name/ {
        proxy_pass http://127.0.0.1/remote/;
    }
  • If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:
    location /some/path/ {
        proxy_pass http://127.0.0.1;
    }

    Before version 1.1.12, if proxy_pass is specified without a URI, the original request URI might be passed instead of the changed URI in some cases.

In some cases, the part of a request URI to be replaced cannot be determined:

  • When location is specified using a regular expression. In this case, the directive should be specified without a URI.
  • When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):
    location /name/ {
        rewrite    /name/([^/]+) /users?name=$1 break;
        proxy_pass http://127.0.0.1;
    }

    In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

A server name, its port and the passed URI can also be specified using variables:

proxy_pass http://$host$uri;

or even like this:

proxy_pass $request;

In this case, the server name is searched among the described server groups, and, if not found, is determined using a resolver. WebSocket proxying requires special configuration and is supported since version 1.3.13.

field
default:
 
context: http, server, location
 

Permits passing proxy_hide_header otherwise disabled header fields from a proxied server to a client.

time
default: 60s
 
context: http, server, location
 

Defines a timeout for reading a response from the proxied server. A timeout is set only between two successive read operations, not for the transmission of the whole response. If a proxied server does not transmit anything within this time, a connection is closed.

on |
default: on
 
context: http, server, location
 

Indicates whether the original request body is passed to the proxied server.

location /x-accel-redirect-here/ {
    proxy_method GET;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_pass ...
}

See also the proxy_set_header and proxy_pass_request_headers directives.

on |
default: on
 
context: http, server, location
 

Indicates whether the header fields of the original request are passed to the proxied server.

location /x-accel-redirect-here/ {
    proxy_method GET;
    proxy_pass_request_headers off;
    proxy_pass_request_body off;
    proxy_pass ...
}

See also the proxy_set_header and proxy_pass_request_body directives.

default
 
off
 
redirect replacement
default: default
 
context: http, server, location
 

Sets the text that should be changed in the Location and Refresh header fields of a proxied server response. Suppose a proxied server returned the header field "Location: http://localhost:8000/two/some/uri/". The directive

proxy_redirect http://localhost:8000/two/ http://frontend/one/;

will rewrite this string to "Location: http://frontend/one/some/uri/". A server name may be omitted in the replacement string:

proxy_redirect http://localhost:8000/two/ /;

then the primary server's name and port, if different from 80, will be inserted. The default replacement specified by the default parameter uses the parameters of the location and proxy_pass directives. Hence, the two configurations below are equivalent:

location /one/ {
    proxy_pass     http://upstream:port/two/;
    proxy_redirect default;
location /one/ {
    proxy_pass     http://upstream:port/two/;
    proxy_redirect http://upstream:port/two/ /one/;

The default parameter is not permitted if proxy_pass is specified using variables. A replacement string can contain variables:

proxy_redirect http://localhost:8000/ http://$host:$server_port/;

A redirect can also contain (1.1.11) variables:

proxy_redirect http://$proxy_host:8000/ /;

The directive can be specified (1.1.11) using regular expressions. In this case, redirect should either start with the "~" symbol for a case-sensitive matching, or with the "~*" symbols for case-insensitive matching. A regular expression can contain named and positional captures, and replacement can reference them:

proxy_redirect ~^(http://[^:]+):\d+(/.+)$ $1$2;
proxy_redirect ~*/user/([^/]+)/(.+)$      http://$1.example.com/$2;

There could be several proxy_redirect directives:

proxy_redirect default;
proxy_redirect http://localhost:8000/  /;
proxy_redirect http://www.example.com/ /;

The off parameter cancels the effect of all proxy_redirect directives on the current level:

proxy_redirect off;
proxy_redirect default;
proxy_redirect http://localhost:8000/  /;
proxy_redirect http://www.example.com/ /;

Using this directive, it is also possible to add host names to relative redirects issued by a proxied server:

proxy_redirect / /;
size
default: 0
 
context: http, server, location
 

If the directive is set to a non-zero value, nginx will try to minimize the number of send operations on outgoing connections to a proxied server by using either NOTE_LOWAT flag of the kqueue method, or the SO_SNDLOWAT socket option, with the specified size. This directive is ignored on Linux, Solaris, and Windows.

time
default: 60s
 
context: http, server, location
 

Sets a timeout for transmitting a request to the proxied server. A timeout is set only between two successive write operations, not for the transmission of the whole request. If a proxied server does not receive anything within this time, a connection is closed.

value
default:
 
context: http, server, location
 

Allows redefining the request body passed to the proxied server. A value can contain text, variables, and their combination.

field value
default: Host $proxy_host
 
context: http, server, location
 

Allows redefining or appending fields to the request header passed to the proxied server. A value can contain text, variables, and their combinations. These directives are inherited from the previous level if and only if there are no proxy_set_header directives defined on the current level. By default, only two fields are redefined:

proxy_set_header Host       $proxy_host;
proxy_set_header Connection close;

An unchanged Host request header field can be passed like this:

proxy_set_header Host       $http_host;

However, if this field is not present in a client request header then nothing will be passed. In such a case it is better to use the $host variable - its value equals the server name in the Host request header field or the primary server name if this field is not present:

proxy_set_header Host       $host;

In addition, the server name can be passed together with the port of the proxied server:

proxy_set_header Host       $host:$proxy_port;

If the value of a header field is an empty string then this field will not be passed to a proxied server:

proxy_set_header Accept-Encoding "";
ciphers
default: DEFAULT
 
context: http, server, location
 

Specifies the enabled ciphers for requests to a proxied HTTPS server. The ciphers are specified in the format understood by the OpenSSL library. The full list can be viewed using the openssl ciphers command.

on |
default: on
 
context: http, server, location
 

Determines whether SSL sessions can be reused when working with the proxied server. If the errors SSL3_GET_FINISHED:digest check failed appear in the logs, try disabling session reuse.

[SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]
default: SSLv3 TLSv1 TLSv1.1 TLSv1.2
 
context: http, server, location
 

Enables the specified protocols for requests to a proxied HTTPS server.

on | | string
default: off
 
context: http, server, location
 

Enables saving of files to a disk. The on parameter saves files with paths corresponding to the directives alias or root. The off parameter disables saving of files. In addition, the file name can be set explicitly using the string with variables:

proxy_store /data/www$original_uri;

The modification time of files is set according to the received Last-Modified response header field. A response is first written to a temporary file, and then the file is renamed. Starting from version 0.8.9, temporary files and the persistent store can be put on different file systems. However, be aware that in this case a file is copied across two file systems instead of the cheap renaming operation. It is thus recommended that for any given location both saved files and a directory holding temporary files, set by the proxy_temp_path directive, are put on the same file system. This directive can be used to create local copies of static unchangeable files, e.g.:

location /images/ {
    root                   /data/www;
    open_file_cache_errors off;
    error_page             404 = /fetch$uri;
}
location /fetch/ {
    internal;
    proxy_pass             http://backend/;
    proxy_store            on;
    proxy_store_access     user:rw group:rw all:r;
    proxy_temp_path        /data/temp;
    alias                  /data/www/;
}

or like this:

location /images/ {
    root               /data/www;
    error_page         404 = @fetch;
}
location @fetch {
    internal;
    proxy_pass         http://backend;
    proxy_store        on;
    proxy_store_access user:rw group:rw all:r;
    proxy_temp_path    /data/temp;
    root               /data/www;
}
users:permissions ...
default: user:rw
 
context: http, server, location
 

Sets access permissions for newly created files and directories, e.g.:

proxy_store_access user:rw group:rw all:r;

If any group or all access permissions are specified then user permissions may be omitted:

proxy_store_access group:rw all:r;
size
default: 8k | 16k
 
context: http, server, location
 

Limits the size of data written to a temporary file at a time, when buffering of responses from the proxied server to temporary files is enabled. By default, size is limited by two buffers set by the proxy_buffer_size and proxy_buffers directives. The maximum size of a temporary file is set by the proxy_max_temp_file_size directive.

path [level1 [level2 [level3]]]
default: proxy_temp
 
context: http, server, location
 

Defines a directory for storing temporary files with data received from proxied servers. Up to three-level subdirectory hierarchy can be used underneath the specified directory. For example, in the following configuration

proxy_temp_path /spool/nginx/proxy_temp 1 2;

a temporary file might look like this:

/spool/nginx/proxy_temp/7/45/00000123457

This module is not enabled on OpenBSD.

on |
default: off
 
context: location
 

Enables or disables module processing in a surrounding location.

This module is not enabled on OpenBSD.

address | CIDR |
default:
 
context: http, server, location
 

Defines trusted addresses that are known to send correct replacement addresses. If the special value unix: is specified, all UNIX-domain sockets will be trusted. IPv6 addresses are supported starting from versions 1.3.0 and 1.2.1.

field | |
default: X-Real-IP
 
context: http, server, location
 

Defines a request header field used to send the address for a replacement.

on |
default: off
 
context: http, server, location
 

If recursive search is disabled, the original client address that matches one of the trusted addresses is replaced by the last address sent in the request header field defined by the real_ip_header directive. If recursive search is enabled, the original client address that matches one of the trusted addresses is replaced by the last non-trusted address sent in the request header field.

size
default: 64
 
context: server, location
 

Sets the bucket size for the valid referers hash tables. The details of setting up hash tables are provided in a separate document.

size
default: 2048
 
context: server, location
 

Sets the maximum size of the valid referers hash tables. The details of setting up hash tables are provided in a separate document.

none | | | string ...
default:
 
context: server, location
 

Specifies the Referer request header field values that will cause the embedded $invalid_referer variable to be set to an empty string. Otherwise, the variable will be set to 1. Search for a match is case-insensitive. Parameters can be as follows:

the Referer field is missing in the request header;
the Referer field is present in the request header, but its value has been deleted by a firewall or proxy server; such values are strings that do not start with "http://" or "https://";
the Referer request header field contains one of the server names;
arbitrary string
defines a server name and an optional URI prefix. A server name can have an "*" at the beginning or end. During the checking, the server's port in the Referer field is ignored;
regular expression
the first symbol should be a "~". It should be noted that an expression will be matched against the text starting after the "http://" or "https://".

Example:

valid_referers none blocked server_names
               *.example.com example.* www.example.org/galleries/
               ~\.google\.;

default:
 
context: server, location, if
 

Stops processing the current set of Module ngx_http_rewrite_module directives. Example:

if ($slow) {
    limit_rate 10k;
    break;
}
(condition) {...}
default:
 
context: server, location
 

The specified condition is evaluated. If true, this module directives specified inside the braces are executed, and the request is assigned the configuration inside the if directive. Configurations inside the if directives are inherited from the previous configuration level. A condition may be any of the following:

  • a variable name; false if the value of a variable is an empty string or 0; Before version 1.0.1, any string starting with 0 was considered a false value.
  • comparison of a variable with a string using the "=" and "!=" operators;
  • matching of a variable against a regular expression using the "~" (for case-sensitive matching) and "~*" (for case-insensitive matching) operators. Regular expressions can contain captures that are made available for later reuse in the $1 .. $9 variables. Negative operators "!~" and "!~*" are also available. If a regular expression includes the "}" or ";" characters, the whole expressions should be enclosed in single or double quotes.
  • checking of a file existence with the -f and !-f operators;
  • checking of a directory existence with the -d and !-d operators;
  • checking of a file, directory, or symbolic link existence with the -e and !-e operators;
  • checking for an executable file with the -x and !-x operators.

Examples:

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}
if ($http_cookie ~* "id=([^;]+)(?:; |$)") {
    set $id $1;
}
if ($request_method = POST) {
    return 405;
}
if ($slow) {
    limit_rate 10k;
}
if ($invalid_referer) {
    return 403;
}

A value of the $invalid_referer embedded variable is set by the valid_referers directive.

code [text]
 
code URL
 
URL
default:
 
context: server, location, if
 

Stops processing and returns the specified code to a client. The non-standard code 444 closes a connection without sending a response header. Starting from version 0.8.42, it is possible to specify either a redirect URL (for codes 301, 302, 303, and 307), or the response body text (for other codes). A response body text and redirect URL can contain variables. As a special case, a redirect URL can be specified as a URI local to this server, in which case the full redirect URL is formed according to the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect directives. In addition, a URL for temporary redirect with the code 302 can be specified as the sole parameter. Such a parameter should start with the "http://", "https://", or $scheme string. A URL can contain variables. Only the following codes could be returned before version 0.7.51: 204, 400, 402 - 406, 408, 410, 411, 413, 416, and 500 - 504. The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.

regex replacement [flag]
default:
 
context: server, location, if
 

If the specified regular expression matches a URI, the URI is changed as specified in the replacement string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with "http://" or "https://", the processing stops and the redirect is returned to a client. An optional flag parameter can be one of:

stops processing the current set of Module ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
stops processing the current set of Module ngx_http_rewrite_module directives;
returns a temporary redirect with the 302 code; used if a replacement string does not start with "http://" or "https://";
returns a permanent redirect with the 301 code.

The full redirect URL is formed according to the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect directives. Example:

server {
    ...
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  last;
    return  403;
    ...
}

But if these directives are put inside the "/download/" location, the last flag should be replaced by break, or otherwise nginx will make 10 cycles and return the 500 error:

location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  break;
    return  403;
}

If a replacement string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

rewrite ^/users/(.*)$ /show?user=$1? last;

If a regular expression includes the "}" or ";" characters, the whole expressions should be enclosed in single or double quotes.

on |
default: off
 
context: http, server, location, if
 

Enables or disables logging of Module ngx_http_rewrite_module module directives processing results into the error_log at the notice level.

variable value
default:
 
context: server, location, if
 

Sets a value for the specified variable. A value can contain text, variables, and their combination.

on |
default: on
 
context: http, server, location, if
 

Controls whether warnings about uninitialized variables are logged.

This module is not enabled on OpenBSD.

default:
 
context: http, server, location
 

Defines a string with variables from which the checksum value and lifetime of a link will be extracted. Variables used in an expression are usually associated with a request; see secure_link_md5 example below. The checksum value extracted from the string is compared with the MD5 hash value of the expression defined by the secure_link_md5 directive. If the checksums are different, the $secure_link variable is set to an empty string. If the checksums are the same, the link lifetime is checked. If the link has a limited lifetime and the time has expired, the $secure_link variable is set to 0. Otherwise, it is set to 1. The MD5 hash value passed in a request is encoded in base64url. If a link has a limited lifetime, the expiration time is set in seconds since Epoch (Thu, 01 Jan 1970 00:00:00 GMT). The value is specified in the expression after the MD5 hash, and is separated by a comma. The expiration time passed in a request is available through the $secure_link_expires variable for a use in the secure_link_md5 directive. If the expiration time is not specified, a link has the unlimited lifetime.

default:
 
context: http, server, location
 

Defines an expression for which the MD5 hash value will be computed and compared with the value passed in a request. The expression should contain the secured part of a link (resource) and a secret ingredient. If the link has a limited lifetime, the expression should also contain $secure_link_expires. To prevent unauthorized access, the expression may contain some information about the client, such as its address and browser version. Example:

location /s/ {
    secure_link $arg_md5,$arg_expires;
    secure_link_md5 "$secure_link_expires$uri$remote_addr secret";
    if ($secure_link = "") {
        return 403;
    }
    if ($secure_link = "0") {
        return 410;
    }
    ...
}

The "/s/link?md5=_e4Nc3iduzkWRm01TBBNYw&expires=2147483647" link restricts access to "/s/link" for the client with the IP address 127.0.0.1. The link also has the limited lifetime until January 19, 2038 (GMT). On UNIX, the md5 request argument value can be obtained as:

echo -n '2147483647/s/link127.0.0.1 secret'  | \
    openssl md5 -binary  | openssl base64  | tr +/ -_  | tr -d =
default:
 
context: location
 

Defines a secret word used to check authenticity of requested links. The full URI of a requested link looks as follows:

/prefix/hash/link

where hash is a hexadecimal representation of the MD5 hash computed for the concatenation of the link and secret word, and prefix is an arbitrary string without slashes. If the requested link passes the authenticity check, the $secure_link variable is set to the link extracted from the request URI. Otherwise, the $secure_link variable is set to an empty string. Example:

location /p/ {
    secure_link_secret secret;
    if ($secure_link = "") {
        return 403;
    }
    rewrite ^ /secure/$secure_link;
}
location /secure/ {
    internal;
}

A request of "/p/5e814704a28d9bc1914ff19fa0c4a00a/link" will be internally redirected to "/secure/link". On UNIX, the hash value for this example can be obtained as:

echo -n 'linksecret'  | openssl md5 -hex

This module is only available in the commercial version of nginx.

name string ...
default: combined "..."
 
context: http
 

Specifies the output format of a log. The value of the $body_bytes_sent variable is aggregated across all requests in a session. The values of all other variables available for logging correspond to the first request in a session.

path zone=name:size [format=format] [timeout=time] [id=id] [md5=md5]
default:
 
context: http
 

Sets the path to a log file and configures the shared memory zone that is used to store currently active sessions. A session is considered active for as long as the time elapsed since the last request in the session does not exceed the specified timeout (by default, 30 seconds). Once a session is no longer active, it is written to the log. The id parameter identifies the session to which a request is mapped. The id parameter is set to the hexadecimal representation of an MD5 hash (for example, obtained from a cookie using variables). If this parameter is not specified or does not represent the valid MD5 hash, nginx computes the MD5 hash from the value of the md5 parameter and creates a new session using this hash. Both the id and md5 parameters can contain variables. The format parameter sets the custom session log format configured by the session_log_format directive. If format is not specified, the predefined combined format is used.

name |
default: off
 
context: http, server, location
 

Enables the use of the specified session log. The special value off cancels all session_log directives inherited from the previous configuration level.

This module is not enabled on OpenBSD.

level
default: 0
 
context: http, server
 

Sets the header compression level of a response in a range from 1 (fastest, less compression) to 9 (slowest, best compression). The special value 0 turns off the header compression.

string $variable {...}
default:
 
context: http
 

Creates a variable for A/B testing, for example:

split_clients "${remote_addr}AAA" $variant {
               0.5%               .one;
               2.0%               .two;
               *                  "";
}

The value of the original string is hashed using MurmurHash2. In the example given, hash values from 0 to 21474835 (0.5%) correspond to the value ".one" of the $variant variable, hash values from 21474836 to 107374180 (2%) correspond to the value ".two", and hash values from 107374181 to 4294967295 correspond to the value "" (an empty string).

on |
default: off
 
context: http, server, location, if in location
 

Enables or disables processing of SSI commands in responses.

on |
default: off
 
context: http, server, location
 

Allows preserving the Last-Modified header field from the original response during SSI processing to facilitate response caching. By default, the header field is removed as contents of the response are modified during processing and may contain dynamically generated elements or parts that are changed independently of the original response.

size
default: 1k
 
context: http, server, location
 

Sets the minimum size for parts of a response stored on disk, starting from which it makes sense to send them using sendfile.

on |
default: off
 
context: http, server, location
 

If enabled, suppresses the output of the "an error occurred while processing the directive" string if an error occurred during SSI processing.

mime-type ...
default: text/html
 
context: http, server, location
 

Enables processing of SSI commands in responses with the specified MIME types in addition to text/html. The special value "*" matches any MIME type (0.8.29).

length
default: 256
 
context: http, server, location
 

Sets the maximum length of parameter values in SSI commands.

on |
default: off
 
context: http, server
 

Enables the HTTPS protocol for the given virtual server. It is recommended to use the ssl parameter of the listen directive instead of this directive.

file
default:
 
context: http, server
 

Specifies a file with the certificate in the PEM format for the given virtual server. If intermediate certificates should be specified in addition to a primary certificate, they should be specified in the same file in the following order: the primary certificate comes first, then the intermediate certificates. A secret key in the PEM format may be placed in the same file. It should be kept in mind that due to the HTTPS protocol limitations virtual servers should listen on different IP addresses:

server {
    listen          192.168.1.1:443;
    server_name     one.example.com;
    ssl_certificate /usr/local/nginx/conf/one.example.com.cert;
    ...
}
server {
    listen          192.168.1.2:443;
    server_name     two.example.com;
    ssl_certificate /usr/local/nginx/conf/two.example.com.cert;
    ...
}

otherwise the first server's certificate will be issued for the second site.

file
default:
 
context: http, server
 

Specifies a file with the secret key in the PEM format for the given virtual server.

ciphers
default: HIGH:!aNULL:!MD5
 
context: http, server
 

Specifies the enabled ciphers. The ciphers are specified in the format understood by the OpenSSL library, for example:

ssl_ciphers ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;

The full list can be viewed using the openssl ciphers command. The previous versions of nginx used different ciphers by default.

file
default:
 
context: http, server
 

Specifies a file with trusted CA certificates in the PEM format used to verify client certificates and OCSP responses if ssl_stapling is enabled. The list of certificates will be sent to clients. If this is not desired, the ssl_trusted_certificate directive can be used.

file
default:
 
context: http, server
 

Specifies a file with revoked certificates (CRL) in the PEM format used to verify client certificates.

file
default:
 
context: http, server
 

Specifies a file with DH parameters for EDH ciphers.

on |
default: off
 
context: http, server
 

Specifies that server ciphers should be preferred over client ciphers when using the SSLv3 and TLS protocols.

[SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]
default: SSLv3 TLSv1 TLSv1.1 TLSv1.2
 
context: http, server
 

Enables the specified protocols. The TLSv1.1 and TLSv1.2 parameters work only when the OpenSSL library of version 1.0.1 or higher is used. The TLSv1.1 and TLSv1.2 parameters are supported starting from versions 1.1.13 and 1.0.12, so when the OpenSSL version 1.0.1 or higher is used on older nginx versions, these protocols work, but cannot be disabled.

off | | [builtin[:size]] [shared: name: size]
default: none
 
context: http, server
 

Sets the types and sizes of caches that store session parameters. A cache can be of any of the following types:

the use of a session cache is strictly prohibited: nginx explicitly tells a client that sessions may not be reused.
the use of a session cache is gently disallowed: nginx tells a client that sessions may be reused, but does not actually store session parameters in the cache.
a cache built in OpenSSL; used by one worker process only. The cache size is specified in sessions. If size is not given, it is equal to 20480 sessions. Use of the built-in cache can cause memory fragmentation.
a cache shared between all worker processes. The cache size is specified in bytes; one megabyte can store about 4000 sessions. Each shared cache should have an arbitrary name. A cache with the same name can be used in several virtual servers.

Both cache types can be used simultaneously, for example:

ssl_session_cache builtin:1000 shared:SSL:10m;

but using only shared cache without the built-in cache should be more efficient.

time
default: 5m
 
context: http, server
 

Specifies a time during which a client may reuse the session parameters stored in a cache.

on |
default: off
 
context: http, server
 

Enables or disables stapling of OCSP responses by the server. Example:

ssl_stapling on;
resolver 192.0.2.1;

For the OCSP stapling to work, the certificate of the server certificate issuer should be known. If the ssl_certificate file does not contain intermediate certificates, the certificate of the server certificate issuer should be present in the ssl_trusted_certificate file. For a resolution of the OCSP responder hostname, the resolver directive should also be specified.

file
default:
 
context: http, server
 

When set, the stapled OCSP response will be taken from the specified file instead of querying the OCSP responder specified in the server certificate. The file should be in the DER format as produced by the openssl ocsp command.

url
default:
 
context: http, server
 

Overrides the URL of the OCSP responder specified in the Authority Information Access certificate extension. Only "http://" OCSP responders are supported:

ssl_stapling_responder http://ocsp.example.com/;
on |
default: off
 
context: http, server
 

Enables or disables verification of OCSP responses by the server. For verification to work, the certificate of the server certificate issuer, the root certificate, and all intermediate certificates should be configured as trusted using the ssl_trusted_certificate directive.

file
default:
 
context: http, server
 

Specifies a file with trusted CA certificates in the PEM format used to verify client certificates and OCSP responses if ssl_stapling is enabled. In contrast to the certificate set by ssl_client_certificate, the list of these certificates will not be sent to clients.

on | | |
default: off
 
context: http, server
 

Enables verification of client certificates. The verification result is stored in the $ssl_client_verify variable. The optional parameter (0.8.7+) requests the client certificate and verifies it if the certificate is present. The optional_no_ca parameter (1.3.8, 1.2.5) requests the client certificate but does not require it to be signed by a trusted CA certificate. This is intended for the use in cases when a service that is external to nginx performs the actual certificate verification. The contents of the certificate is accessible through the $ssl_client_cert variable.

number
default: 1
 
context: http, server
 

Sets the verification depth in the client certificates chain.

This module is only available in the commercial version of nginx.

default:
 
context: location
 

The status information will be accessible from the surrounding location.

json
 
jsonp [callback]
default: json
 
context: http, server, location
 

By default, status information is output in the JSON format. Alternatively, data may be output as JSONP. The callback parameter specifies the name of a callback function. The value can contain variables. If parameter is omitted, or the computed value is an empty string, then Module ngx_status_jsonp_callback is used.

on
default:
 
context: location
 

The status information will be accessible from the surrounding location.

This module is not enabled on OpenBSD.

string replacement
default:
 
context: http, server, location
 

Sets a string to replace and a replacement string. The string to replace is matched ignoring the case. The replacement string can contain variables.

on |
default: off
 
context: http, server, location
 

Allows preserving the Last-Modified header field from the original response during replacement to facilitate response caching. By default, the header field is removed as contents of the response are modified during processing.

on |
default: on
 
context: http, server, location
 

Indicates whether to look for a string to replace once or several times.

mime-type ...
default: text/html
 
context: http, server, location
 

Enables string replacement in responses with the specified MIME types in addition to text/html. The special value "*" matches any MIME type (0.8.29).

name {...}
default:
 
context: http
 

Defines a group of servers. Servers can listen on different ports. In addition, servers listening on TCP and UNIX-domain sockets can be mixed. Example:

upstream backend {
    server backend1.example.com weight=5;
    server 127.0.0.1:8080       max_fails=3 fail_timeout=30s;
    server unix:/tmp/backend3;
}

By default, requests are distributed between the servers using a weighted round-robin balancing method. In the above example, each 7 requests will be distributed as follows: 5 requests go to backend1.example.com and one request to each of the second and third servers. If an error occurs during communication with a server, the request will be passed to the next server, and so on until all of the functioning servers will be tried. If a successful response could not be obtained from any of the servers, the client will receive the result of the communication with the last server.

address [parameters]
default:
 
context: upstream
 

Defines the address and other parameters of a server. The address can be specified as a domain name or IP address, with an optional port, or as a UNIX-domain socket path specified after the unix: prefix. If a port is not specified, the port 80 is used. A domain name that resolves to several IP addresses defines multiple servers at once. The following parameters can be defined:

=number
sets the weight of the server, by default, 1.
=number
sets the number of unsuccessful attempts to communicate with the server that should happen in the duration set by the fail_timeout parameter to consider the server unavailable for a duration also set by the fail_timeout parameter. By default, the number of unsuccessful attempts is set to 1. The zero value disables the accounting of attempts. What is considered an unsuccessful attempt is defined by the proxy_next_upstream, fastcgi_next_upstream, and memcached_next_upstream directives.
=time
sets
  • the time during which the specified number of unsuccessful attempts to communicate with the server should happen to consider the server unavailable;
  • and the period of time the server will be considered unavailable.

By default, the parameter is set to 10 seconds.

=time
sets the time during which the server will recover its weight from zero to a nominal value, when unhealthy server becomes healthy, or when the server becomes available after a period of time it was considered unavailable. Default value is zero, i.e. slow start is disabled.

This option is only available in the commercial version of nginx.

marks the server as a backup server. It will be passed requests when the primary servers are unavailable.
marks the server as permanently unavailable; used along with the ip_hash directive.
=string
sets the server route name.

This option is only available in the commercial version of nginx.

Example:

upstream backend {
    server backend1.example.com     weight=5;
    server 127.0.0.1:8080           max_fails=3 fail_timeout=30s;
    server unix:/tmp/backend3;
    server backup1.example.com:8080 backup;
}

If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable.

name size
default:
 
context: upstream
 

This directive is only available in the commercial version of nginx.

Makes the group dynamically configurable. Defines the name and size of a shared memory zone that keeps group's configuration and run-time state that are shared between worker processes. Such groups allow to add, remove, and modify servers at run time. The configuration is accessible via a special location handled by upstream_conf.

default:
 
context: upstream
 

Specifies that a group should use a load balancing method where requests are distributed between servers based on client IP addresses. The first three octets of the client IPv4 address, or the entire IPv6 address, are used as a hashing key. The method ensures that requests from the same client will always be passed to the same server except when this server is unavailable. In the latter case client requests will be passed to another server. Most probably, it will always be the same server as well. IPv6 addresses are supported starting from versions 1.3.2 and 1.2.2. If one of the servers needs to be temporarily removed, it should be marked with the down parameter in order to preserve the current hashing of client IP addresses. Example:

upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com down;
    server backend4.example.com;
}

Until versions 1.3.1 and 1.2.2, it was not possible to specify a weight for servers using the ip_hash load balancing method.

connections
default:
 
context: upstream
 

Activates the cache for connections to upstream servers. The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed. It should be particularly noted that the keepalive directive does not limit the total number of connections to upstream servers that an nginx worker process can open. The connections parameter should be set to a number small enough to let upstream servers process new incoming connections as well. Example configuration of memcached upstream with keepalive connections:

upstream memcached_backend {
    server 127.0.0.1:11211;
    server 10.0.0.2:11211;
    keepalive 32;
}
server {
    ...
    location /memcached/ {
        set $memcached_key $uri;
        memcached_pass memcached_backend;
    }
}

For HTTP, the proxy_http_version directive should be set to 1.1 and the Connection header field should be cleared:

upstream http_backend {
    server 127.0.0.1:8080;
    keepalive 16;
}
server {
    ...
    location /http/ {
        proxy_pass http://http_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        ...
    }
}

Alternatively, HTTP/1.0 persistent connections can be used by passing the Connection: Keep-Alive header field to an upstream server, though this method is not recommended. For FastCGI servers, it is required to set fastcgi_keep_conn for keepalive connections to work:

upstream fastcgi_backend {
    server 127.0.0.1:9000;
    keepalive 8;
}
server {
    ...
    location /fastcgi/ {
        fastcgi_pass fastcgi_backend;
        fastcgi_keep_conn on;
        ...
    }
}

When using load balancer methods other than the default round-robin method, it is necessary to activate them before the keepalive directive. SCGI and uwsgi protocols do not have a notion of keepalive connections.

default:
 
context: upstream
 

Specifies that a group should use a load balancing method where a request is passed to the server with the least number of active connections, taking into account weights of servers. If there are several such servers, they are tried using a weighted round-robin balancing method.

[interval=time] [fails=number] [passes=number] [uri=uri] [match=name]
default:
 
context: location
 

This directive is only available in the commercial version of nginx.

Enables periodic health checks of the servers in a upstream group referenced in the surrounding location. The following optional parameters are supported:

  • sets the interval between two consecutive health checks, by default, 5 seconds;
  • sets the number of consecutive failed health checks of a particular server after which this server will be considered unhealthy, by default, 1;
  • sets the number of consecutive passed health checks of a particular server after which the server will be considered healthy, by default, 1;
  • uri defines the URI used in health check requests, by default, "/";
  • specifies the match block configuring the tests that a response should pass in order for a health check to pass; by default, the response should have status code 2xx or 3xx.

For example,

location / {
    proxy_pass http://backend;
    health_check;
}

will send "/" requests to each server in the backend group every five seconds. If any communication error or timeout occurs, or a proxied server responds with the status code other than 2xx or 3xx, the health check will fail, and the server will be considered unhealthy. Client requests are not passed to unhealthy servers. Health checks can be configured to test the status code of a response, presence of certain header fields and their values, and the body contents. Tests are configured separately using the match directive and referenced in the match parameter. For example:

http {
    server {
    ...
        location / {
            proxy_pass http://backend;
            health_check match=welcome;
        }
    }
    match welcome {
        status 200;
        header Content-Type = text/html;
        body ~ "Welcome to nginx!";
    }
}

This configuration tells that for a health check to pass, the response to a health check request should succeed, have status 200, content type text/html, and contain "Welcome to nginx!" in the body. The server group must reside in the shared memory. If several health checks are defined for the same group of servers, a single failure of any check will make the corresponding server be considered unhealthy.

name {...}
default:
 
context: http
 

This directive is only available in the commercial version of nginx.

Defines the named test set used to verify responses to health check requests. The following items can be tested in a response:

status is 200
! 500;
status is not 500
status is 200 or 204
! 301 302;
status is neither 301 nor 302
status is in the range from 200 to 399
! 400-599;
status is not in the range from 400 to 599
status is either 301, 302, 303, or 307
header contains Content-Type with value text/html
!=text/html;
header contains Content-Type with value other than text/html
header contains Connection with value matching regular expression close
header contains Connection with value not matching regular expression close
header contains Host
! X-Accel-Redirect;
header lacks X-Accel-Redirect
;
body matches regular expression Welcome to nginx!
;
body does not match regular expression Welcome to nginx!

If several tests are specified, the response matches only if it matches all tests. Only the first 256k of the response body are examined. Examples:

# status is 200, content type is "text/html",
# and body contains "Welcome to nginx!"
match welcome {
    status 200;
    header Content-Type = text/html;
    body ~ "Welcome to nginx!";
}
# status is not one of 301, 302, 303, or 307, and header does not have "Refresh:"
match not_redirect {
    status ! 301-303 307;
    header ! Refresh;
}
# status ok and not in maintenance mode
match server_ok {
    status 200-399;
    body !~ "maintenance mode";
}
cookie name [expires=time] [domain=domain] [path=path]
 
route variable ...
default:
 
context: upstream
 

This directive is only available in the commercial version of nginx.

Enables session affinity, which causes requests from the same client to be passed to the same server in a group of servers. Two methods are available, cookie and route. When the cookie method is used, information about the designated server is passed in an HTTP cookie:

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    sticky cookie srv_id expires=1h domain=.example.com path=/;
}

A request that comes from a client not yet bound to a particular server is passed to the server selected by the configured balancing method. Further requests from the same client are passed to the same server. If the designated server cannot process a request, the new server is selected as if the client has not been bound yet. The first parameter sets the name of the cookie to be set or inspected. Additional parameters may be as follows:

Sets the time for which a browser should keep the cookie. The special value max will cause the cookie to expire on 31 Dec 2037 23:55:55 GMT. This is the maximum time understood by old browsers. If the parameter is not specified, it will cause the cookie to expire at the end of a browser session.
Defines the domain for which the cookie is set.
Defines the path for which the cookie is set.

If any parameters are omitted, the corresponding cookie fields are not set. When the route method is used, proxied server assigns client a route on receipt of the first request. All subsequent requests from this client will carry routing information in a cookie or URI. This information is compared with the route parameter of the server directive to identify the server to which the request should be proxied. If the designated server cannot process a request, the new server is selected by the configured balancing method as if there is no routing information in the request. The parameters of the route method specify variables that may contain routing information. The first non-empty variable is used to find the matching server. Example:

map $cookie_jsessionid $route_cookie {
    ~.+\.(?P<route>\w+)$ $route;
}
map $request_uri $route_uri {
    ~jsessionid=.+\.(?P<route>\w+)$ $route;
}
upstream backend {
    server backend1.example.com route=a;
    server backend2.example.com route=b;
    sticky route $route_cookie $route_uri;
}

Here, the route is taken from the JSESSIONID cookie if present in a request. Otherwise, the route from the URI is used.

default:
 
context: upstream
 

This directive is obsolete since version 1.5.7. An equivalent sticky directive with a new syntax should be used instead: sticky cookie name [expires=time] [domain=domain] [path=path];

default:
 
context: location
 

This directive is only available in the commercial version of nginx.

Turns on the HTTP interface of upstream configuration in the surrounding location. Access to this location should be satisfy limited . Configuration commands can be used to:

  • view all primary or backup servers in a group;
  • view an individual server;
  • modify an individual server;
  • add a new server (see the note below);
  • remove an individual server.

As noted in the server directive, specifying a server as a domain name may result in several servers being added to the group. Since addresses in a group are not required to be unique, individual servers in a group can be uniquely referenced to only by their ID. IDs are assigned automatically and shown on viewing of the group configuration. A configuration command consists of parameters passed as request arguments, for example:

http://127.0.0.1/upstream_conf?upstream=appservers

The following parameters are supported:

=name
Selects a group. This parameter is mandatory.
=
If not set, selects primary servers in the group. If set, selects backup servers in the group.
=number
Selects an individual primary or backup server in the group.
=
Removes an individual primary or backup server from the group.
=
Adds a new primary or backup server to the group.
=address
Same as the address parameter of the server directive.
=number
Same as the weight parameter of the server directive.
=number
Same as the max_fails parameter of the server directive.
=time
Same as the fail_timeout parameter of the server directive.
=time
Same as the slow_start parameter of the server directive.
=
Same as the down parameter of the server directive.
=
The opposite of the down parameter of the server directive.
=string
Same as the route parameter of the server directive.

The first three parameters select a target the command applies to. Without other parameters, the command shows configuration of the selected target. For example, to view the primary servers in the group, send:

http://127.0.0.1/upstream_conf?upstream=appservers

To view the backup servers in the group, send:

http://127.0.0.1/upstream_conf?upstream=appservers&backup=

To view an individual primary server in the group, send:

http://127.0.0.1/upstream_conf?upstream=appservers&id=42

To view an individual backup server in the group, send:

http://127.0.0.1/upstream_conf?upstream=appservers&backup=&id=42

To add a new primary or backup server to the group, specify its address in the server= parameter. Without other parameters specified, a server will be added with other parameters set to their default values (see the server directive). For example, to add a new primary server to the group, send:

http://127.0.0.1/upstream_conf?add=&upstream=appservers&server=127.0.0.1:8080

To add a new backup server to the group, send:

http://127.0.0.1/upstream_conf?add=&upstream=appservers&backup=&server=127.0.0.1:8080

To add a new primary server to the group, set its parameters to non-default values and mark it as down, send:

http://127.0.0.1/upstream_conf?add=&upstream=appservers&server=127.0.0.1:8080&weight=2&max_fails=3&fail_timeout=3s&down=

To remove an individual primary or backup server from the group, select it with the id= parameter. For example, to remove an individual primary server from the group, send:

http://127.0.0.1/upstream_conf?remove=&upstream=appservers&id=42

To remove an individual backup server from the group, send:

http://127.0.0.1/upstream_conf?remove=&upstream=appservers&backup=&id=42

To modify an individual primary or backup server in the group, select it with the id= parameter. For example, to modify an individual primary server in the group by marking it as down, send:

http://127.0.0.1/upstream_conf?upstream=appservers&id=42&down=

To modify the address of an individual backup server in the group, send:

http://127.0.0.1/upstream_conf?upstream=appservers&backup=&id=42&server=192.0.2.3:8123

To modify other parameters of an individual primary server in the group, send:

http://127.0.0.1/upstream_conf?upstream=appservers&id=42&max_fails=3&weight=4

on | | |
default: off
 
context: http, server, location
 

Enables or disables setting cookies and logging the received cookies:

enables the setting of version 2 cookies and logging of the received cookies;
enables the setting of version 1 cookies and logging of the received cookies;
disables the setting of cookies, but enables logging of the received cookies;
disables the setting of cookies and logging of the received cookies.
name |
default: none
 
context: http, server, location
 

Defines a domain for which the cookie is set. The none parameter disables setting of a domain for the cookie.

time | |
default: off
 
context: http, server, location
 

Sets a time during which a browser should keep the cookie. The parameter max will cause the cookie to expire on 31 Dec 2037 23:55:55 GMT. This is the maximum time understood by old browsers. The parameter off will cause the cookie to expire at the end of a browser session.

letter | digit |=|
default: off
 
context: http, server, location
 

If the parameter is not off, enables the cookie marking mechanism and sets the character used as a mark. This mechanism is used to add or change userid_p3p and/or a cookie expiration time while preserving the client identifier. A mark can be any letter of the English alphabet (case-sensitive), digit, or the "=" character. If the mark is set, it is compared with the first padding symbol in the base64 representation of the client identifier passed in a cookie. If they do not match, the cookie is resent with the specified mark, expiration time, and P3P header.

name
default: uid
 
context: http, server, location
 

Sets the cookie name.

string |
default: none
 
context: http, server, location
 

Sets a value for the P3P header field that will be sent along with the cookie. If the directive is set to the special value none, the P3P header will not be sent in a response.

path
default: /
 
context: http, server, location
 

Defines a path for which the cookie is set.

number
default: IP address of the server
 
context: http, server, location
 

If identifiers are issued by multiple servers (services), each service should be assigned its own number to ensure that client identifiers are unique. For version 1 cookies, the default value is zero. For version 2 cookies, the default value is the number composed from the last four octets of the server's IP address.

This module is not enabled on OpenBSD.

path
default:
 
context: http, server, location
 

Specifies the DTD file that declares character entities. This file is compiled at the configuration stage. For technical reasons, the module is unable to use the external subset declared in the processed XML, so it is ignored and a specially defined file is used instead. This file should not describe the XML structure. It is enough to declare just the required character entities, for example:

<!ENTITY nbsp "&#xa0;">
on |
default: off
 
context: http, server, location
 

Allows preserving the Last-Modified header field from the original response during XSLT transformations to facilitate response caching. By default, the header field is removed as contents of the response are modified during transformations and may contain dynamically generated elements or parts that are changed independently of the original response.

parameter value
default:
 
context: http, server, location
 

Defines the parameters for XSLT stylesheets. The value is treated as an XPath expression. The value can contain variables. To pass a string value to a stylesheet, the xslt_string_param directive can be used. There could be several xslt_param directives. These directives are inherited from the previous level if and only if there are no xslt_param and xslt_string_param directives defined on the current level.

parameter value
default:
 
context: http, server, location
 

Defines the string parameters for XSLT stylesheets. XPath expressions in the value are not interpreted. The value can contain variables. There could be several xslt_string_param directives. These directives are inherited from the previous level if and only if there are no xslt_param and xslt_string_param directives defined on the current level.

stylesheet [parameter=value ...]
default:
 
context: location
 

Defines the XSLT stylesheet and its optional parameters. A stylesheet is compiled at the configuration stage. Parameters can either be specified separately, or grouped in a single line using the ":" delimiter. If a parameter includes the ":" character, it should be escaped as "%3A". Also, libxslt requires to enclose parameters that contain non-alphanumeric characters into single or double quotes, for example:

param1='http%3A//www.example.com':param2=value2

The parameters description can contain variables, for example, the whole line of parameters can be taken from a single variable:

location / {
    xslt_stylesheet /site/xslt/one.xslt
                    $arg_xslt_params
                    param1='$value1':param2=value2
                    param3=value3;
}

It is possible to specify several stylesheets. They will be applied sequentially in the specified order.

mime-type ...
default: text/xml
 
context: http, server, location
 

Enables transformations in responses with the specified MIME types in addition to text/xml. The special value "*" matches any MIME type (0.8.29). If the transformation result is an HTML response, its MIME type is changed to text/html.

/etc/nginx/nginx.conf

The following is a valid configuration file, but such creative use of whitespace is not recommended:

worker_processes #whitespace is required here
auto
#a comment is allowed here
;events{}user #whitespace is again required here
www
#and here, too
www;# but not here

nginx(8)

This manual has been available since OpenBSD 5.5.

The bulk of the text was semi-automatically converted from the XML sources of http://nginx.org/en/docs/#development to mdoc(7) by Florian Obser <florian@openbsd.org>. The description of the grammar was written by Ingo Schwarze <schwarze@openbsd.org>.

January 27, 2014 OpenBSD-5.5