Nginx Modules Reference PDF
Nginx Modules Reference PDF
1
Preface
About NGINX
NGINX® (“engine x”) is a high performance, high concurrency web server
excelling at large scale content delivery, web acceleration and protecting
application containers. Its precise integration with modern operating systems
allows unprecedented levels of efficiency even when running on commodity
hardware.
Nginx, Inc. develops and maintains NGINX open source distribution, and
offers commercial support and professional services for NGINX.
• NGINX and NGINX Plus Tutorial and Admin Guide is available here:
https://www.nginx.com/resources/admin-guide/.
2
Contents
Title 1
Preface 2
Table of Contents 3
1 Core modules 6
1.1 Core functionality . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Setting up hashes . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.3 Connection processing methods . . . . . . . . . . . . . . . . . . 17
1.4 Logging to syslog . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3
CONTENTS CONTENTS
5 Miscellaneous 441
5.1 High Availability support for NGINX Plus . . . . . . . . . . . . 441
5.2 Command-line parameters . . . . . . . . . . . . . . . . . . . . . 447
Index 460
Core modules
6
CHAPTER 1. CORE MODULES 1.1. CORE FUNCTIONALITY
events {
use kqueue;
worker_connections 2048;
}
...
1.1.2 Directives
accept mutex
Syntax: accept_mutex on | off;
Default off
Context: events
daemon
Syntax: daemon on | off;
Default on
Context: main
debug connection
Syntax: debug_connection address | CIDR | unix:;
Default —
Context: events
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:;
...
}
debug points
Syntax: debug_points abort | stop;
Default —
Context: main
env
Syntax: env variable[=value];
Default TZ
Context: main
The TZ variable is always inherited and available to the 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;
error log
Syntax: error_log file [level];
Default logs/error.log error
Context: main, http, mail, stream, server, location
Configures logging. Several logs can be specified on the same level (1.5.2).
If on the main configuration level writing a log to a file is not explicitly defined,
the default file will be used.
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. Logging to a cyclic
memory buffer can be configured by specifying the “memory:” prefix and
buffer size, and is generally used for debugging (1.7.11).
The second parameter determines the level of logging, and can be one of the
following: debug, info, notice, warn, error, crit, alert, or emerg.
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.
The directive can be specified on the stream level starting from version
1.7.11, and on the mail level starting from version 1.9.0.
events
Syntax: events { . . . }
Default —
Context: main
Provides the configuration file context in which the directives that affect
connection processing are specified.
include
Syntax: include file | mask;
Default —
Context: any
include mime.types;
include vhosts/*.conf;
load module
Syntax: load_module file;
Default —
Context: main
This directive appeared in version 1.9.11.
load_module modules/ngx_mail_module.so;
lock file
Syntax: lock_file 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.
master process
Syntax: master_process on | off;
Default on
Context: main
multi accept
Syntax: multi_accept on | off;
Default off
Context: events
pcre jit
Syntax: pcre_jit on | off;
Default off
Context: main
This directive appeared in version 1.1.12.
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.
pid
Syntax: pid file;
Default logs/nginx.pid
Context: main
Defines a file that will store the process ID of the main process.
ssl engine
Syntax: ssl_engine device;
Default —
Context: main
thread pool
Syntax: thread_pool name threads=number [max_queue=number];
Default default threads=32 max_queue=65536
Context: main
This directive appeared in version 1.7.11.
Defines named thread pools used for multi-threaded reading and sending
of files without blocking worker processes.
The threads parameter defines the number of threads in the pool.
In the event that all threads in the pool are busy, a new task will wait in
the queue. The max_queue parameter limits the number of tasks allowed to
be waiting in the queue. By default, up to 65536 tasks can wait in the queue.
When the queue overflows, the task is completed with an error.
timer resolution
Syntax: timer_resolution interval;
Default —
Context: main
timer_resolution 100ms;
• setitimer otherwise.
use
Syntax: use method;
Default —
Context: events
user
Syntax: user user [group];
Default nobody nobody
Context: main
When using aio with the epoll connection processing method, sets the
maximum number of outstanding asynchronous I/O operations for a single
worker process.
worker connections
Syntax: worker_connections number;
Default 512
Context: events
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;
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 special value auto (1.9.10) allows binding worker processes
automatically to available CPUs:
worker_processes auto;
worker_cpu_affinity auto;
The optional mask parameter can be used to limit the CPUs available for
automatic binding:
worker priority
Syntax: worker_priority 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;
worker processes
Syntax: worker_processes number | auto;
Default 1
Context: main
The auto parameter is supported starting from versions 1.3.8 and 1.2.5.
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.
working directory
Syntax: working_directory directory;
Default —
Context: main
1.2.1 Overview
To quickly process static sets of data such as server names, map directive’s
values, MIME types, names of request header strings, nginx uses hash tables.
During the start and each re-configuration nginx selects the minimum possible
sizes of hash tables such that the bucket size that stores keys with identical
hash values does not exceed the configured parameter (hash bucket size). The
size of a table is expressed in buckets. The adjustment is continued until
the table size exceeds the hash max size parameter. Most hashes have the
corresponding directives that allow changing these parameters, for example,
for the server names hash they are server names hash max size and server -
names hash bucket size.
The hash bucket size parameter is aligned to the size that is a multiple of
the processor’s cache line size. This speeds up key search in a hash on modern
processors by reducing the number of memory accesses. If hash bucket size is
equal to one processor’s cache line size then the number of memory accesses
during the key search will be two in the worst case — first to compute the
bucket address, and second during the key search inside the bucket. Therefore,
if nginx emits the message requesting to increase either hash max size or hash
bucket size then the first parameter should first be increased.
1.3.1 Overview
nginx supports a variety of connection processing methods. The availability
of a particular method depends on the platform used. On platforms that
support several methods nginx will normally select the most efficient method
automatically. However, if needed, a connection processing method can be
selected explicitly with the use directive.
The following connection processing methods are supported:
Some older distributions like SuSE 8.2 provide patches that add epoll
support to 2.4 kernels.
1.4.1 Overview
The error log and access log directives support logging to syslog. The
following parameters configure logging to syslog:
server=address
Defines the address of a syslog 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 port is not specified, the
UDP port 514 is used. If a domain name resolves to several IP addresses,
the first resolved address is used.
facility=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”.
severity=string
Sets severity of syslog messages for access log, as defined in RFC 3164.
Possible values are the same as for the second parameter (level) of the
error log directive. Default is “info”.
tag=string
Sets the tag of syslog messages. Default is “nginx”.
nohostname
Disables adding the “hostname” field into the syslog message header
(1.9.7).
access_log syslog:server=unix:/var/log/nginx.sock,nohostname;
access_log syslog:server=[2001:db8::1]:12345,facility=local7,tag=nginx,severity
=info combined;
19
CHAPTER 2. HTTP SERVER MODULES 2.1. MODULE NGX HTTP CORE MODULE
2.1.1 Directives
absolute redirect
Syntax: absolute_redirect on | off;
Default on
Context: http, server, location
This directive appeared in version 1.11.8.
aio
Syntax: aio on | off | threads[=pool];
Default off
Context: http, server, location
This directive appeared in version 0.8.11.
Enables or disables the use of asynchronous file I/O (AIO) on FreeBSD and
Linux:
location /video/ {
aio on;
output_buffers 1 64k;
}
options VFS_AIO
kldload aio
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.
When both AIO and sendfile are enabled on Linux, AIO is used for files
that are larger than or equal to the size specified in the directio directive, while
sendfile is used for files of smaller sizes or when directio is disabled.
location /video/ {
sendfile on;
aio on;
directio 8m;
}
Finally, files can be read and sent using multi-threading (1.7.11), without
blocking a worker process:
location /video/ {
sendfile on;
aio threads;
}
Read and send file operations are offloaded to threads of the specified pool.
If the pool name is omitted, the pool with the name “default” is used. The
pool name can also be set with variables:
aio threads=pool$disk;
aio write
Syntax: aio_write on | off;
Default off
Context: http, server, location
This directive appeared in version 1.9.13.
alias
Syntax: alias path;
Default —
Context: location
Defines a replacement for the specified location. For example, with the
following configuration
location /i/ {
alias /data/w3/images/;
}
location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
alias /data/w3/images/$1;
}
location /images/ {
alias /data/w3/images/;
}
location /images/ {
root /data/w3;
}
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 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.
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 $r->request body file method of the 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.
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.
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;
/spool/nginx/client_temp/7/45/00000123457
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 request is terminated with the 408 Request Time-out error.
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.
Defines a timeout for reading client request header. If a client does not
transmit the entire header within this time, the request is terminated with the
408 Request Time-out error.
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.
Prior to version 1.9.8, the default value was 256 on all platforms.
default type
Syntax: default_type mime-type;
Default text/plain
Context: http, server, location
directio
Syntax: directio size | off;
Default off
Context: http, server, location
This directive appeared in version 0.7.7.
Enables the use of the O_DIRECT flag (FreeBSD, Linux), the F_NOCACHE
flag (macOS), or the directio 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;
directio alignment
Syntax: directio_alignment size;
Default 512
Context: http, server, location
This directive appeared in version 0.8.11.
disable symlinks
Syntax: disable_symlinks off;
Syntax: disable_symlinks on | if_not_owner [from=part];
Default off
Context: http, server, location
This directive appeared in version 1.1.15.
off
Symbolic links in the pathname are allowed and not checked. This is the
default behavior.
on
If any component of the pathname is a symbolic link, access to a file is
denied.
if_not_owner
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.
from=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 openat and
fstatat interfaces. Such systems include modern versions of FreeBSD,
Linux, and Solaris.
Parameters on and if_not_owner add a processing overhead.
The ngx http autoindex module, ngx http random index module, and
ngx http dav module modules currently ignore this directive.
error page
Syntax: error_page code . . . [=[response]] uri;
Default —
Context: http, server, location, if in location
Defines the URI that will be shown for the specified errors. A uri value can
contain variables.
Example:
This causes an internal redirect to the specified uri with the client request
method changed to “GET” (for all methods other than “GET” and “HEAD”).
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.
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, 307,
and 308).
The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.
The code 308 was not treated as a redirect until version 1.13.0.
These directives are inherited from the previous level if and only if there
are no error_page directives defined on the current level.
etag
Syntax: etag on | off;
Default on
Context: http, server, location
This directive appeared in version 1.3.3.
http
Syntax: http { . . . }
Default —
Context: main
Provides the configuration file context in which the HTTP server directives
are specified.
if modified since
Syntax: if_modified_since off | exact | before;
Default exact
Context: http, server, location
This directive appeared in version 0.7.24.
off
the If-Modified-Since request header field is ignored (0.7.34);
exact
exact match;
before
modification time of a response is less than or equal to the time in the
If-Modified-Since request header field.
internal
Syntax: internal;
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;
Example:
location = /404.html {
internal;
}
keepalive disable
Syntax: keepalive_disable none | browser . . . ;
Default msie6
Context: http, server, location
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.
keepalive requests
Syntax: keepalive_requests number;
Default 100
Context: http, server, location
This directive appeared in version 0.8.0.
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.
keepalive timeout
Syntax: keepalive_timeout timeout [header timeout];
Default 75s
Context: http, server, location
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.
limit except
Syntax: limit_except method . . . { . . . }
Default —
Context: location
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.
limit rate
Syntax: limit_rate rate;
Default 0
Context: http, server, location, if in location
server {
if ($slow) {
set $limit_rate 4k;
}
...
}
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;
}
lingering close
Syntax: lingering_close off | on | always;
Default on
Context: http, server, location
This directive appeared in versions 1.1.0 and 1.0.6.
lingering time
Syntax: lingering_time 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.
lingering timeout
Syntax: lingering_timeout time;
Default 5s
Context: http, server, location
listen
Syntax: listen address[:port] [default_server] [ssl] [http2 | spdy]
[proxy_protocol] [setfib=number] [fastopen=number]
[backlog=number] [rcvbuf=size] [sndbuf=size]
[accept_filter=filter] [deferred] [bind] [ipv6only=on|off]
[reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Syntax: listen port [default_server] [ssl] [http2 | spdy]
[proxy_protocol] [setfib=number] [fastopen=number]
[backlog=number] [rcvbuf=size] [sndbuf=size]
[accept_filter=filter] [deferred] [bind] [ipv6only=on|off]
[reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Syntax: listen unix:path [default_server] [ssl] [http2 | spdy]
[proxy_protocol] [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;
listen [::]:8000;
listen [::1];
listen unix:/var/run/nginx.sock;
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.
setfib=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.
fastopen=number
enables “TCP Fast Open” for the listening socket (1.5.8) and limits
the maximum length for the queue of connections that have not yet
completed the three-way handshake.
Do not enable this feature unless the server can handle receiving the
same SYN packet with data more than once.
backlog=number
sets the backlog parameter in the listen call that limits the
maximum length for the queue of pending connections. By default,
backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS, and
to 511 on other platforms.
rcvbuf=size
sets the receive buffer size (the SO_RCVBUF option) for the listening
socket.
sndbuf=size
sets the send buffer size (the SO_SNDBUF option) for the listening socket.
accept_filter=filter
sets the name of accept filter (the SO_ACCEPTFILTER option) for the
listening socket that filters incoming connections before passing them
to accept. This works only on FreeBSD and NetBSD 5.0+. Possible
values are dataready and httpready.
deferred
instructs to use a deferred accept (the TCP_DEFER_ACCEPT socket
option) on Linux.
bind
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 getsockname system call will be made in
this case to determine the address that accepted the connection. If the
setfib, backlog, rcvbuf, sndbuf, accept_filter, deferred,
ipv6only, or so_keepalive parameters are used then for a given
address:port pair a separate bind call will always be made.
ipv6only=on|off
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.
reuseport
this parameter (1.9.1) instructs to create an individual listening socket for
each worker process (using the SO_REUSEPORT socket option on Linux
3.9+ and DragonFly BSD, or SO_REUSEPORT_LB on FreeBSD 12+),
allowing a kernel to distribute incoming connections between worker
processes. This currently works only on Linux 3.9+, DragonFly BSD,
and FreeBSD 12+ (1.15.1).
so_keepalive=on|off|[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:
location
Syntax: location [ = | ~ | ~* | ˆ~ ] uri { . . . }
Syntax: location @name { . . . }
Default —
Context: server, location
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
location /user/ {
proxy_pass http://user.example.com;
}
location = /user {
proxy_pass http://login.example.com;
}
Enables or disables logging of errors about not found files into error log.
log subrequest
Syntax: log_subrequest on | off;
Default off
Context: http, server, location
max ranges
Syntax: max_ranges number;
Default —
Context: http, server, location
This directive appeared in version 1.1.2.
merge slashes
Syntax: merge_slashes on | off;
Default on
Context: http, server
location /scripts/ {
...
}
msie padding
Syntax: msie_padding on | off;
Default on
Context: http, server, location
msie refresh
Syntax: msie_refresh on | off;
Default off
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.
Sets a time after which open file cache elements should be validated.
output buffers
Syntax: output_buffers number size;
Default 2 32k
Context: http, server, location
Sets the number and size of the buffers used for reading a response from a
disk.
port in redirect
Syntax: port_in_redirect on | off;
Default on
Context: http, server, location
postpone output
Syntax: postpone_output size;
Default 1460
Context: http, server, location
read ahead
Syntax: read_ahead size;
Default 0
Context: http, server, location
Sets the amount of pre-reading for the kernel when working with file.
On Linux, the posix_fadvise(0, 0, 0, POSIX_FADV_SEQUEN-
TIAL) system call is used, and so the size parameter is ignored.
On FreeBSD, the fcntl(O_READAHEAD, size) system call, supported
since FreeBSD 9.0-CURRENT, is used. FreeBSD 7 has to be patched.
Enables or disables doing several redirects using the error page directive.
The number of such redirects is limited.
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.
resolver
Syntax: resolver address . . . [valid=time] [ipv6=on|off];
Default —
Context: http, server, location
By default, nginx will look up both IPv4 and IPv6 addresses while resolving.
If looking up of IPv6 addresses is not desired, the ipv6=off parameter can
be specified.
Before version 1.1.9, tuning of caching time was not possible, and nginx
always cached answers for the duration of 5 minutes.
resolver timeout
Syntax: resolver_timeout time;
Default 30s
Context: http, server, location
resolver_timeout 5s;
root
Syntax: root 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;
}
satisfy
Syntax: satisfy all | any;
Default all
Context: http, server, location
Allows access if all (all) or at least one (any) of the ngx http -
access module, ngx http auth basic module, ngx http auth request module,
or ngx http auth jwt module modules allow access.
Example:
location / {
satisfy any;
allow 192.168.1.0/32;
deny all;
send lowat
Syntax: send_lowat 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.
send timeout
Syntax: send_timeout time;
Default 60s
Context: http, server, location
Sets a timeout for transmitting a response to the client. The timeout is set
only between two successive write operations, not for the transmission of the
whole response. If the client does not receive anything within this time, the
connection is closed.
sendfile
Syntax: sendfile on | off;
Default off
Context: http, server, location, if in location
location /video/ {
sendfile on;
tcp_nopush on;
aio on;
}
When set to a non-zero value, limits the amount of data that can be
transferred in a single sendfile call. Without the limit, one fast connection
may seize the worker process entirely.
server
Syntax: server { . . . }
Default —
Context: http
server name
Syntax: server_name name . . . ;
Default ""
Context: server
server {
server_name example.com www.example.com;
}
server {
server_name example.com *.example.com www.example.*;
}
server {
server_name .example.com;
}
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;
}
}
server {
server_name ~^(www\.)?(?<domain>.+)$;
location / {
root /sites/$domain;
}
}
server {
server_name _;
location / {
root /sites/default;
}
}
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.
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:
1. the exact name
2. the longest wildcard name starting with an asterisk, e.g.
“*.example.com”
Enables or disables the use of the primary server name, specified by the
server name directive, in absolute 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.
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.
Sets the maximum size of the server names hash tables. The details of
setting up hash tables are provided in a separate document.
server tokens
Syntax: server_tokens on | off | build | string;
Default on
Context: http, server, location
can be set explicitly using the string with variables. An empty string disables
the emission of the Server field.
Sets the size of the buffer used for storing the response body of a subrequest.
By default, the buffer size is equal to one memory page. This is either 4K or
8K, depending on a platform. It can be made smaller, however.
The directive is applicable only for subrequests with response bodies saved
into memory. For example, such subrequests are created by SSI.
tcp nodelay
Syntax: tcp_nodelay on | off;
Default on
Context: http, server, location
tcp nopush
Syntax: tcp_nopush on | off;
Default off
Context: http, server, location
try files
Syntax: try_files file . . . uri;
Syntax: try_files 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;
}
location / {
try_files $uri $uri/index.html $uri.html =404;
}
location / {
try_files /system/maintenance.html
$uri $uri/index.html $uri.html
@mongrel;
}
location @mongrel {
proxy_pass http://mongrel;
}
location / {
try_files $uri $uri/ @drupal;
}
location ~ \.php$ {
try_files $uri @drupal;
fastcgi_pass ...;
location @drupal {
fastcgi_pass ...;
location / {
try_files $uri $uri/ @drupal;
}
location / {
error_page 404 = @drupal;
log_not_found off;
}
And here,
location ~ \.php$ {
try_files $uri @drupal;
fastcgi_pass ...;
...
}
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 ...;
location @wordpress {
fastcgi_pass ...;
types
Syntax: types { . . . }
Default text/html html; image/gif gif; image/jpeg jpg;
Context: http, server, location
types {
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
}
location /download/ {
types { }
default_type application/octet-stream;
}
Sets the bucket size for the types hash tables. The details of setting up
hash tables are provided in a separate document.
Prior to version 1.5.13, the default value depended on the size of the
processor’s cache line.
Sets the maximum size of the types hash tables. The details of setting up
hash tables are provided in a separate document.
underscores in headers
Syntax: underscores_in_headers on | off;
Default off
Context: http, server
Sets the bucket size for the variables hash table. The details of setting up
hash tables are provided in a separate document.
Sets the maximum size of the variables hash table. The details of setting
up hash tables are provided in a separate document.
$cookie name
the name cookie
$document root
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)
$proxy protocol addr
client address from the PROXY protocol header, or an empty string
otherwise (1.5.12)
The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter in the listen directive.
$proxy protocol port
client port from the PROXY protocol header, or an empty string
otherwise (1.11.0)
The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter in the listen directive.
$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, fastcgi pass, uwsgi pass, and scgi pass directives when the
request body was read to a memory buffer.
$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/uwsgi/SCGI server, passing the request body
should be disabled by the proxy pass request body off, fastcgi pass -
request body off, uwsgi pass request body off, or scgi 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 id
unique request identifier generated from 16 random bytes, in hexadecimal
(1.11.0)
$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
$sent trailer name
arbitrary field sent at the end of the response (1.13.2); 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”, “HTTP/1.1”, or “HTTP/2.0”
$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.
2.2.1 Summary
The ngx_http_access_module module allows limiting access to
certain client addresses.
Access can also be limited by password, by the result of subrequest, or
by JWT. Simultaneous limitation of access by address and by password is
controlled by the satisfy directive.
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
The rules are checked in sequence until the first match is found. In
this example, access is allowed only for IPv4 networks 10.1.1.0/16 and
192.168.1.0/24 excluding the address 192.168.1.1, and for IPv6
network 2001:0db8::/32. In case of a lot of rules, the use of the ngx -
http geo module module variables is preferable.
2.2.3 Directives
allow
Syntax: allow address | CIDR | unix: | all;
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.
deny
Syntax: deny address | CIDR | unix: | all;
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.
2.3.1 Summary
The ngx_http_addition_module module is a filter that adds text
before and after a response. This module is not built by default, it should
be enabled with the --with-http_addition_module configuration
parameter.
location / {
add_before_body /before_action;
add_after_body /after_action;
}
2.3.3 Directives
add before body
Syntax: add_before_body uri;
Default —
Context: http, server, location
addition types
Syntax: addition_types mime-type . . . ;
Default text/html
Context: http, server, location
This directive appeared in version 0.7.9.
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).
2.4.1 Summary
The ngx_http_api_module module (1.13.3) provides REST API for
accessing various status information, configuring upstream server groups on-
the-fly, and managing key-value pairs without the need of reconfiguring nginx.
The module supersedes the ngx http status module and ngx http -
upstream conf module modules.
http {
upstream backend {
zone http_backend 64k;
server {
server_name backend.example.com;
location / {
proxy_pass http://backend;
proxy_cache cache_backend;
health_check;
}
status_zone server_backend;
}
server {
listen 127.0.0.1;
location /api {
api write=on;
allow 127.0.0.1;
deny all;
}
}
}
stream {
upstream backend {
zone stream_backend 64k;
server {
listen 127.0.0.1:12345;
proxy_pass backend;
status_zone server_backend;
health_check;
}
}
All API requests include a supported API version in the URI. Examples of
API requests with this configuration:
http://127.0.0.1/api/3/
http://127.0.0.1/api/3/nginx
http://127.0.0.1/api/3/connections
http://127.0.0.1/api/3/http/requests
http://127.0.0.1/api/3/http/server_zones/server_backend
http://127.0.0.1/api/3/http/caches/cache_backend
http://127.0.0.1/api/3/http/upstreams/backend
http://127.0.0.1/api/3/http/upstreams/backend/servers/
http://127.0.0.1/api/3/http/upstreams/backend/servers/1
http://127.0.0.1/api/3/http/keyvals/one?key=arg1
http://127.0.0.1/api/3/stream/
http://127.0.0.1/api/3/stream/server_zones/server_backend
http://127.0.0.1/api/3/stream/upstreams/
http://127.0.0.1/api/3/stream/upstreams/backend
http://127.0.0.1/api/3/stream/upstreams/backend/servers/1
2.4.3 Directives
api
Syntax: api [write=on|off];
Default —
Context: location
http://127.0.0.1/api/3/nginx?fields=version,build
status zone
Syntax: status_zone zone;
Default —
Context: server
This directive appeared in version 1.13.12.
2.4.4 Compatibility
• The /stream/zone sync/ data were added in version 3.
2.4.5 Endpoints
/
Supported methods:
• GET - Return list of root endpoints
Returns a list of root endpoints.
Possible responses:
– 200 - Success, returns an array of strings
/nginx
Supported methods:
• GET - Return status of nginx running instance
Returns nginx version, build name, address, number of configuration
reloads, IDs of master and worker processes.
Request parameters:
fields (string, optional)
Limits which fields of nginx running instance will be output.
Possible responses:
– 200 - Success, returns nginx
/processes
Supported methods:
/slabs/
Supported methods:
• GET - Return status of all slabs
Returns status of slabs for each shared memory zone with slab
allocator.
Request parameters:
fields (string, optional)
Limits which fields of slab zones will be output. If the“fields”
value is empty, then only zone names are output.
Possible responses:
– 200 - Success, returns a collection of ”Shared memory zone with
slab allocator” objects for all slabs
/slabs/{slabZoneName}
Parameters common for all methods:
slabZoneName (string, required)
The name of the shared memory zone with slab allocator.
Supported methods:
• GET - Return status of a slab
Returns status of slabs for a particular shared memory zone with
slab allocator.
Request parameters:
fields (string, optional)
Limits which fields of the slab zone will be output.
Possible responses:
– 200 - Success, returns Shared memory zone with slab allocator
– 404 - Slab not found (SlabNotFound), returns Error
DELETE - Reset slab statistics
Resets the “reqs” and “fails” metrics for each memory slot.
Possible responses:
• – 204 - Success
– 404 - Slab not found (SlabNotFound), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
/http/
Supported methods:
• GET - Return list of HTTP-related endpoints
Returns a list of first level HTTP endpoints.
Possible responses:
– 200 - Success, returns an array of strings
/http/requests
Supported methods:
• GET - Return HTTP requests statistics
Returns status of client HTTP requests.
Request parameters:
fields (string, optional)
Limits which fields of client HTTP requests statistics will be
output.
Possible responses:
– 200 - Success, returns HTTP Requests
DELETE - Reset HTTP requests statistics
Resets the number of total client HTTP requests.
Possible responses:
• – 204 - Success
– 405 - Method disabled (MethodDisabled), returns Error
/http/server_zones/
Supported methods:
• GET - Return status of all HTTP server zones
Returns status information for each HTTP server zone.
Request parameters:
fields (string, optional)
Limits which fields of server zones will be output. If the
“fields” value is empty, then only server zone names are
output.
Possible responses:
– 200 - Success, returns a collection of ”HTTP Server Zone”
objects for all http server zones
/http/server_zones/{httpServerZoneName}
Parameters common for all methods:
httpServerZoneName (string, required)
The name of an HTTP server zone.
Supported methods:
• GET - Return status of an HTTP server zone
Returns status of a particular HTTP server zone.
Request parameters:
fields (string, optional)
Limits which fields of the server zone will be output.
Possible responses:
/http/keyvals/{httpKeyvalZoneName}
Parameters common for all methods:
httpKeyvalZoneName (string, required)
The name of an HTTP keyval shared memory zone.
Supported methods:
• GET - Return key-value pairs from an HTTP keyval zone
Returns key-value pairs stored in a particular HTTP keyval shared
memory zone.
Request parameters:
key (string, optional)
Get a particular key-value pair from the HTTP keyval zone.
Possible responses:
– 200 - Success, returns HTTP Keyval Shared Memory Zone
– 404 - Keyval not found (KeyvalNotFound), keyval key not
found (KeyvalKeyNotFound), returns Error
POST - Add a key-value pair to the HTTP keyval zone
Adds a new key-value pair to the HTTP keyval shared memory
zone. Several key-value pairs can be entered if the HTTP keyval
shared memory zone is empty.
Request parameters:
• Key-value (HTTP Keyval Shared Memory Zone, required)
A key-value pair is specified in the JSON format. Several key-
value pairs can be entered if the HTTP keyval shared memory
zone is empty.
Possible responses:
– 201 - Created
– 400 - Key required (KeyvalFormatError), only one key
can be added (KeyvalFormatError), nested object or list
(KeyvalFormatError), returns Error
– 404 - Keyval not found (KeyvalNotFound), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
– 409 - Key already exists (KeyvalKeyExists), returns Error
– 415 - JSON error (JsonError), returns Error
PATCH - Modify a key-value or delete a key
Changes the value of the selected key in the key-value pair or deletes
a key by setting the key value to null.
Request parameters:
• httpKeyvalZoneKeyValue (HTTP Keyval Shared Memory
Zone, required)
A new value for the key is specified in the JSON format.
Possible responses:
– 204 - Success
– 400 - Key required (KeyvalFormatError), only one key
can be updated (KeyvalFormatError), nested object or list
(KeyvalFormatError), returns Error
– 404 - Keyval not found (KeyvalNotFound), keyval key not
found (KeyvalKeyNotFound), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
– 415 - JSON error (JsonError), returns Error
DELETE - Empty the HTTP keyval zone
Deletes all key-value pairs from the HTTP keyval shared memory
zone.
Possible responses:
• – 204 - Success
– 404 - Keyval not found (KeyvalNotFound), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
/stream/
Supported methods:
• GET - Return list of stream-related endpoints
Returns a list of first level stream endpoints.
Possible responses:
– 200 - Success, returns an array of strings
/stream/server_zones/
Supported methods:
• GET - Return status of all stream server zones
Returns status information for each stream server zone.
Request parameters:
fields (string, optional)
Limits which fields of server zones will be output. If the
“fields” value is empty, then only server zone names are
output.
Possible responses:
– 200 - Success, returns a collection of ”Stream Server Zone”
objects for all stream server zones
– 404 - stream not configured (StreamNotConfigured),
returns Error
/stream/server_zones/{streamServerZoneName}
Parameters common for all methods:
streamServerZoneName (string, required)
The name of a stream server zone.
Supported methods:
• GET - Return status of a stream server zone
Returns status of a particular stream server zone.
Request parameters:
fields (string, optional)
Limits which fields of the server zone will be output.
Possible responses:
– 200 - Success, returns Stream Server Zone
– 404 - Server zone not found (ServerZoneNotFound), stream
not configured (StreamNotConfigured), returns Error
DELETE - Reset statistics for a stream server zone
Resets statistics of accepted and discarded connections, sessions,
received and sent bytes in a particular stream server zone.
Possible responses:
• – 204 - Success
– 404 - Server zone not found (ServerZoneNotFound), stream
not configured (StreamNotConfigured), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
/stream/upstreams/
Supported methods:
• GET - Return status of all stream upstream server groups
Returns status of each stream upstream server group and its servers.
Request parameters:
fields (string, optional)
Limits which fields of upstream server groups will be output.
If the “fields” value is empty, only names of upstreams are
output.
Possible responses:
– 200 - Success, returns a collection of ”Stream Upstream” objects
for all stream upstreams
– 404 - stream not configured (StreamNotConfigured),
returns Error
/stream/upstreams/{streamUpstreamName}/
Parameters common for all methods:
streamUpstreamName (string, required)
The name of a stream upstream server group.
Supported methods:
Request parameters:
• Key-value (Stream Keyval Shared Memory Zone, required)
A key-value pair is specified in the JSON format. Several key-
value pairs can be entered if the stream keyval shared memory
zone is empty.
Possible responses:
– 201 - Created
– 400 - Key required (KeyvalFormatError), only one key
can be added (KeyvalFormatError), nested object or list
(KeyvalFormatError), returns Error
– 404 - Keyval not found (KeyvalNotFound), stream not
configured (StreamNotConfigured), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
– 409 - Key already exists (KeyvalKeyExists), returns Error
– 415 - JSON error (JsonError), returns Error
PATCH - Modify a key-value or delete a key
Changes the value of the selected key in the key-value pair or deletes
a key by setting the key value to null.
Request parameters:
• streamKeyvalZoneKeyValue (Stream Keyval Shared Memory
Zone, required)
A new value for the key is specified in the JSON format.
Possible responses:
– 204 - Success
– 400 - Key required (KeyvalFormatError), only one key
can be updated (KeyvalFormatError), nested object or list
(KeyvalFormatError), returns Error
– 404 - Keyval not found (KeyvalNotFound), keyval key
not found (KeyvalKeyNotFound), stream not configured
(StreamNotConfigured), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
– 415 - JSON error (JsonError), returns Error
DELETE - Empty the stream keyval zone
Deletes all key-value pairs from the stream keyval shared memory
zone.
Possible responses:
• – 204 - Success
– 404 - Keyval not found (KeyvalNotFound), stream not
configured (StreamNotConfigured), returns Error
– 405 - Method disabled (MethodDisabled), returns Error
/stream/zone_sync/
Supported methods:
• GET - Return sync status of a node
Returns synchronization status of a cluster node.
Possible responses:
– 200 - Success, returns Stream Zone Sync Node
– 404 - Zone sync not configured (ZoneSyncNotConfigured),
stream not configured (StreamNotConfigured), returns
Error
version (string)
Version of nginx.
build (string)
Name of nginx build.
address (string)
The address of the server that accepted status request.
generation (integer)
The total number of configuration reloads.
load_timestamp (string)
Time of the last reload of configuration, in milliseconds since Epoch.
timestamp (string)
Current time in milliseconds since Epoch.
pid (integer)
The ID of the worker process that handled status request.
ppid (integer)
The ID of the master process that started the worker process.
Example:
{
"nginx" : {
"version" : "1.13.3",
"build" : "nginx-plus-r12-p3",
"address" : "206.251.255.64",
"generation" : 2,
"load_timestamp" : "2017-07-07T11:09:21.594Z",
"timestamp" : "2017-07-11T09:31:13.477Z",
"pid" : 32212,
"ppid" : 32210
}
}
• Processes:
respawned (integer)
The total number of abnormally terminated and respawned child
processes.
Example:
{
"respawned" : 0
}
• Connections:
The number of accepted, dropped, active, and idle connections.
accepted (integer)
The total number of accepted client connections.
dropped (integer)
The total number of dropped client connections.
active (integer)
The current number of active client connections.
idle (integer)
The current number of idle client connections.
Example:
{
"accepted" : 4968119,
"dropped" : 0,
"active" : 5,
"idle" : 117
}
• SSL:
handshakes (integer)
The total number of successful SSL handshakes.
handshakes_failed (integer)
The total number of failed SSL handshakes.
session_reuses (integer)
The total number of session reuses during SSL handshake.
Example:
{
"handshakes" : 79572,
"handshakes_failed" : 21025,
"session_reuses" : 15762
}
pages
The number of free and used memory pages.
used (integer)
The current number of used memory pages.
free (integer)
The current number of free memory pages.
slots
Status data for memory slots (8, 16, 32, 64, 128, etc.)
A collection of ”Memory Slot” objects
Example:
{
"pages" : {
"used" : 1143,
"free" : 2928
},
"slots" : {
"8" : {
"used" : 0,
"free" : 0,
"reqs" : 0,
"fails" : 0
},
"16" : {
"used" : 0,
"free" : 0,
"reqs" : 0,
"fails" : 0
},
"32" : {
"used" : 0,
"free" : 0,
"reqs" : 0,
"fails" : 0
},
"64" : {
"used" : 1,
"free" : 63,
"reqs" : 1,
"fails" : 0
},
"128" : {
"used" : 0,
"free" : 0,
"reqs" : 0,
"fails" : 0
},
"256" : {
"used" : 18078,
"free" : 178,
"reqs" : 1635736,
"fails" : 0
}
}
}
• Memory Slot:
used (integer)
The current number of used memory slots.
free (integer)
The current number of free memory slots.
reqs (integer)
The total number of attempts to allocate memory of specified size.
fails (integer)
The number of unsuccessful attempts to allocate memory of
specified size.
HTTP Requests:
• total (integer)
The total number of client requests.
current (integer)
The current number of client requests.
Example:
{
"total" : 10624511,
"current" : 4
}
processing (integer)
The number of client requests that are currently being processed.
requests (integer)
The total number of client requests received from clients.
responses
The total number of responses sent to clients and the number of
responses with status codes “1xx”, “2xx”, “3xx”, “4xx”, and “5xx”.
1xx (integer)
The number of responses with “1xx” status codes.
2xx (integer)
The number of responses with “2xx” status codes.
3xx (integer)
The number of responses with “3xx” status codes.
4xx (integer)
The number of responses with “4xx” status codes.
5xx (integer)
The number of responses with “5xx” status codes.
total (integer)
The total number of responses sent to clients.
discarded (integer)
The total number of requests completed without sending a response.
received (integer)
The total number of bytes received from clients.
sent (integer)
The total number of bytes sent to clients.
Example:
{
"processing" : 1,
"requests" : 706690,
"responses" : {
"1xx" : 0,
"2xx" : 699482,
"3xx" : 4522,
"4xx" : 907,
"5xx" : 266,
"total" : 705177
},
"discarded" : 1513,
"received" : 172711587,
"sent" : 19415530115
}
• HTTP Cache:
size (integer)
The current size of the cache.
max_size (integer)
The limit on the maximum size of the cache specified in the
configuration.
cold (boolean)
A boolean value indicating whether the “cache loader” process is
still loading data from disk into the cache.
hit
responses (integer)
The total number of valid responses read from the cache.
bytes (integer)
The total number of bytes read from the cache.
stale
responses (integer)
The total number of expired responses read from the cache
(see proxy cache use stale and other “*_cache_use_stale”
directives).
bytes (integer)
The total number of bytes read from the cache.
updating
responses (integer)
The total number of expired responses read from the cache while
responses were being updated (see proxy cache use stale and
other “*_cache_use_stale” directives).
bytes (integer)
The total number of bytes read from the cache.
revalidated
responses (integer)
The total number of expired and revalidated responses read
from the cache (see proxy cache revalidate and other “*_-
cache_revalidate” directives.
bytes (integer)
The total number of bytes read from the cache.
miss
responses (integer)
The total number of responses not found in the cache.
bytes (integer)
The total number of bytes read from the proxied server.
responses_written (integer)
The total number of responses written to the cache.
bytes_written (integer)
The total number of bytes written to the cache.
expired
responses (integer)
The total number of expired responses not taken from the cache.
bytes (integer)
The total number of bytes read from the proxied server.
responses_written (integer)
The total number of responses written to the cache.
bytes_written (integer)
The total number of bytes written to the cache.
bypass
responses (integer)
The total number of responses not looked up in the cache
due to the proxy cache bypass and other “*_cache_bypass”
directives.
bytes (integer)
The total number of bytes read from the proxied server.
responses_written (integer)
The total number of responses written to the cache.
bytes_written (integer)
The total number of bytes written to the cache.
Example:
{
"size" : 530915328,
"max_size" : 536870912,
"cold" : false,
"hit" : {
"responses" : 254032,
"bytes" : 6685627875
},
"stale" : {
"responses" : 0,
"bytes" : 0
},
"updating" : {
"responses" : 0,
"bytes" : 0
},
"revalidated" : {
"responses" : 0,
"bytes" : 0
},
"miss" : {
"responses" : 1619201,
"bytes" : 53841943822
},
"expired" : {
"responses" : 45859,
"bytes" : 1656847080,
"responses_written" : 44992,
"bytes_written" : 1641825173
},
"bypass" : {
"responses" : 200187,
"bytes" : 5510647548,
"responses_written" : 200173,
"bytes_written" : 44992
}
}
• HTTP Upstream:
peers
An array of:
id (integer)
The ID of the server.
server (string)
An address of the server.
service (string)
The service parameter value of the server directive.
name (string)
The name of the server specified in the server directive.
backup (boolean)
A boolean value indicating whether the server is a backup
server.
weight (integer)
Weight of the server.
state (string)
Current state, which may be one of “up”, “draining”, “down”,
“unavail”, “checking”, and “unhealthy”.
active (integer)
The current number of active connections.
max_conns (integer)
The max conns limit for the server.
requests (integer)
header_time (integer)
The average time to get the response header from the server.
response_time (integer)
The average time to get the full response from the server.
keepalive (integer)
The current number of idle keepalive connections.
zombies (integer)
The current number of servers removed from the group but still
processing active client requests.
zone (string)
The name of the shared memory zone that keeps the group’s
configuration and run-time state.
queue
For the requests queue, the following data are provided:
size (integer)
The current number of requests in the queue.
max_size (integer)
The maximum number of requests that can be in the queue at
the same time.
overflows (integer)
The total number of requests rejected due to the queue overflow.
Example:
{
"upstream_backend" : {
"peers" : [
{
"id" : 0,
"server" : "10.0.0.1:8088",
"name" : "10.0.0.1:8088",
"backup" : false,
"weight" : 5,
"state" : "up",
"active" : 0,
"max_conns" : 20,
"requests" : 667231,
"header_time" : 20,
"response_time" : 36,
"responses" : {
"1xx" : 0,
"2xx" : 666310,
"3xx" : 0,
"4xx" : 915,
"5xx" : 6,
"total" : 667231
},
"sent" : 251946292,
"received" : 19222475454,
"fails" : 0,
"unavail" : 0,
"health_checks" : {
"checks" : 26214,
"fails" : 0,
"unhealthy" : 0,
"last_passed" : true
},
"downtime" : 0,
"downstart" : "2017-07-07T11:09:21.602Z",
"selected" : "2017-07-17T15:01:25.000Z"
},
{
"id" : 1,
"server" : "10.0.0.1:8089",
"name" : "10.0.0.1:8089",
"backup" : true,
"weight" : 1,
"state" : "unhealthy",
"active" : 0,
"max_conns" : 20,
"requests" : 0,
"responses" : {
"1xx" : 0,
"2xx" : 0,
"3xx" : 0,
"4xx" : 0,
"5xx" : 0,
"total" : 0
},
"sent" : 0,
"received" : 0,
"fails" : 0,
"unavail" : 0,
"health_checks" : {
"checks" : 26284,
"fails" : 26284,
"unhealthy" : 1,
"last_passed" : false
},
"downtime" : 262925617,
"downstart" : "2017-07-07T11:09:21.602Z",
"selected" : "2017-07-17T15:01:25.000Z"
}
],
"keepalive" : 0,
"zombies" : 0,
"zone" : "upstream_backend"
}
}
id (integer)
The ID of the HTTP upstream server. The ID is assigned
automatically and cannot be changed.
server (string)
Same as the address parameter of the HTTP upstream server.
When adding a server, it is possible to specify it as a domain name.
In this case, changes of the IP addresses that correspond to a domain
name will be monitored and automatically applied to the upstream
configuration without the need of restarting nginx. This requires
the resolver directive in the “http” block. See also the resolve
parameter of the HTTP upstream server.
service (string)
Same as the service parameter of the HTTP upstream server. This
parameter cannot be changed.
weight (integer)
Same as the weight parameter of the HTTP upstream server.
max_conns (integer)
Same as the max conns parameter of the HTTP upstream server.
max_fails (integer)
Same as the max fails parameter of the HTTP upstream server.
fail_timeout (string)
Same as the fail timeout parameter of the HTTP upstream server.
slow_start (string)
Same as the slow start parameter of the HTTP upstream server.
route (string)
Same as the route parameter of the HTTP upstream server.
backup (boolean)
When true, adds a backup server. This parameter cannot be
changed.
down (boolean)
Same as the down parameter of the HTTP upstream server.
drain (boolean)
Same as the drain parameter of the HTTP upstream server.
parent (string)
Parent server ID of the resolved server. The ID is assigned
automatically and cannot be changed.
host (string)
Hostname of the resolved server. The hostname is assigned
automatically and cannot be changed.
Example:
{
"id" : 1,
"server" : "10.0.0.1:8089",
"weight" : 4,
"max_conns" : 0,
"max_fails" : 0,
"fail_timeout" : "10s",
"slow_start" : "10s",
"route" : "",
"backup" : true,
"down" : true
}
{
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
processing (integer)
The number of client connections that are currently being processed.
connections (integer)
The total number of connections accepted from clients.
sessions
The total number of completed sessions, and the number of sessions
completed with status codes “2xx”, “4xx”, or “5xx”.
2xx (integer)
The total number of sessions completed with status codes
“2xx”.
4xx (integer)
The total number of sessions completed with status codes
“4xx”.
5xx (integer)
The total number of sessions completed with status codes
“5xx”.
total (integer)
The total number of completed client sessions.
discarded (integer)
The total number of connections completed without creating a
session.
received (integer)
The total number of bytes received from clients.
sent (integer)
The total number of bytes sent to clients.
Example:
{
"dns" : {
"processing" : 1,
"connections" : 155569,
"sessions" : {
"2xx" : 155564,
"4xx" : 0,
"5xx" : 0,
"total" : 155569
},
"discarded" : 0,
"received" : 4200363,
"sent" : 20489184
}
}
• Stream Upstream:
peers
An array of:
id (integer)
The ID of the server.
server (string)
An address of the server.
service (string)
The service parameter value of the server directive.
name (string)
The name of the server specified in the server directive.
backup (boolean)
A boolean value indicating whether the server is a backup
server.
weight (integer)
Weight of the server.
state (string)
Current state, which may be one of “up”, “down”, “unavail”,
“checking”, or “unhealthy”.
active (integer)
The current number of connections.
max_conns (integer)
The max conns limit for the server.
connections (integer)
The total number of client connections forwarded to this server.
connect_time (integer)
The average time to connect to the upstream server.
first_byte_time (integer)
The average time to receive the first byte of data.
response_time (integer)
The average time to receive the last byte of data.
sent (integer)
The total number of bytes sent to this server.
received (integer)
The total number of bytes received from this server.
fails (integer)
The total number of unsuccessful attempts to communicate
with the server.
unavail (integer)
How many times the server became unavailable for client
connections (state “unavail”) due to the number of
unsuccessful attempts reaching the max fails threshold.
health_checks
checks (integer)
The total number of health check requests made.
fails (integer)
The number of failed health checks.
unhealthy (integer)
Example:
{
"dns" : {
"peers" : [
{
"id" : 0,
"server" : "10.0.0.1:12347",
"name" : "10.0.0.1:12347",
"backup" : false,
"weight" : 5,
"state" : "up",
"active" : 0,
"max_conns" : 50,
"connections" : 667231,
"sent" : 251946292,
"received" : 19222475454,
"fails" : 0,
"unavail" : 0,
"health_checks" : {
"checks" : 26214,
"fails" : 0,
"unhealthy" : 0,
"last_passed" : true
},
"downtime" : 0,
"downstart" : "2017-07-07T11:09:21.602Z",
"selected" : "2017-07-17T15:01:25.000Z"
},
{
"id" : 1,
"server" : "10.0.0.1:12348",
"name" : "10.0.0.1:12348",
"backup" : true,
"weight" : 1,
"state" : "unhealthy",
"active" : 0,
"max_conns" : 50,
"connections" : 0,
"sent" : 0,
"received" : 0,
"fails" : 0,
"unavail" : 0,
"health_checks" : {
"checks" : 26284,
"fails" : 26284,
"unhealthy" : 1,
"last_passed" : false
},
"downtime" : 262925617,
"downstart" : "2017-07-07T11:09:21.602Z",
"selected" : "2017-07-17T15:01:25.000Z"
}
],
"zombies" : 0,
"zone" : "dns"
}
}
id (integer)
The ID of the stream upstream server. The ID is assigned
automatically and cannot be changed.
server (string)
Same as the address parameter of the stream upstream server.
When adding a server, it is possible to specify it as a domain name.
In this case, changes of the IP addresses that correspond to a domain
name will be monitored and automatically applied to the upstream
configuration without the need of restarting nginx. This requires
the resolver directive in the “stream” block. See also the resolve
parameter of the stream upstream server.
service (string)
Same as the service parameter of the stream upstream server. This
parameter cannot be changed.
weight (integer)
Same as the weight parameter of the stream upstream server.
max_conns (integer)
Same as the max conns parameter of the stream upstream server.
max_fails (integer)
Same as the max fails parameter of the stream upstream server.
fail_timeout (string)
Same as the fail timeout parameter of the stream upstream server.
slow_start (string)
Same as the slow start parameter of the stream upstream server.
backup (boolean)
When true, adds a backup server. This parameter cannot be
changed.
down (boolean)
Same as the down parameter of the stream upstream server.
parent (string)
Parent server ID of the resolved server. The ID is assigned
automatically and cannot be changed.
host (string)
Hostname of the resolved server. The hostname is assigned
automatically and cannot be changed.
Example:
{
"id" : 0,
"server" : "10.0.0.1:12348",
"weight" : 1,
"max_conns" : 0,
"max_fails" : 1,
"fail_timeout" : "10s",
"slow_start" : 0,
"backup" : false,
"down" : false
}
{
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
zones
Synchronization information per each shared memory zone.
A collection of ”Sync Zone” objects
status
Synchronization information per node in a cluster.
bytes_in (integer)
The number of bytes received by this node.
msgs_in (integer)
The number of messages received by this node.
msgs_out (integer)
The number of messages sent by this node.
bytes_out (integer)
The number of bytes sent by this node.
nodes_online (integer)
The number of peers this node is connected to.
Example:
{
"zones" : {
"zone1" : {
"records_pending" : 2061,
"records_total" : 260575
},
"zone2" : {
"records_pending" : 0,
"records_total" : 14749
}
},
"status" : {
"bytes_in" : 1364923761,
"msgs_in" : 337236,
"msgs_out" : 346717,
"bytes_out" : 1402765472,
"nodes_online" : 15
}
}
• Sync Zone:
Synchronization status of a shared memory zone.
records_pending (integer)
The number of records that need to be sent to the cluster.
records_total (integer)
The total number of records stored in the shared memory zone.
Error:
nginx error object.
• path (string)
API path.
method (string)
HTTP method.
error
status (integer)
HTTP error code.
text (string)
Error description.
code (string)
Internal nginx error code.
request_id (string)
The ID of the request, equals the value of the $request id variable.
href (string)
Link to reference documentation.
2.5.1 Summary
The ngx_http_auth_basic_module module allows limiting access to
resources by validating the user name and password using the “HTTP Basic
Authentication” protocol.
Access can also be limited by address, by the result of subrequest, or
by JWT. Simultaneous limitation of access by address and by password is
controlled by the satisfy directive.
location / {
auth_basic "closed site";
auth_basic_user_file conf/htpasswd;
}
2.5.3 Directives
auth basic
Syntax: auth_basic string | off;
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.
Specifies a file that keeps user names and passwords, in the following format:
# comment
name1:password1
name2:password2:comment
name3:password3
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.
2.6.1 Summary
The ngx_http_auth_jwt_module module (1.11.3) implements client
authorization by validating the provided JSON Web Token (JWT) using the
specified keys. JWT claims must be encoded in a JSON Web Signature (JWS)
structure. The module can be used for OpenID Connect authentication.
The module may be combined with other access modules, such as
ngx http access module, ngx http auth basic module, and ngx http auth -
request module, via the satisfy directive.
The module supports the following cryptographic algorithms:
location / {
auth_jwt "closed site";
auth_jwt_key_file conf/keys.json;
}
2.6.3 Directives
auth jwt
Syntax: auth_jwt string [token=$variable] | off;
Default off
Context: http, server, location, limit except
The special value off cancels the effect of the auth_jwt directive
inherited from the previous configuration level.
Sets the variable to a JWT claim parameter identified by key names. Name
matching starts from the top level of the JSON tree. For arrays, the variable
keeps a list of array elements separated by commas.
location / {
auth_jwt "closed site";
auth_jwt_key_file conf/keys.json;
auth_jwt_claim_set $email info e-mail;
auth_jwt_claim_set $job info "job title";
}
Prior to version 1.13.7, only one key name could be specified, and the
result was undefined for arrays.
Prior to version 1.13.7, only one key name could be specified, and the
result was undefined for arrays.
Specifies a file in JSON Web Key Set format for validating JWT signature.
Parameter value can contain variables.
2.7.1 Summary
The ngx_http_auth_request_module module (1.5.4+) implements
client authorization based on the result of a subrequest. If the subrequest
returns a 2xx response code, the access is allowed. If it returns 401 or 403, the
access is denied with the corresponding error code. Any other response code
returned by the subrequest is considered an error.
For the 401 error, the client also receives the WWW-Authenticate header
from the subrequest response.
This module is not built by default, it should be enabled with the
--with-http_auth_request_module configuration parameter.
The module may be combined with other access modules, such as ngx -
http access module, ngx http auth basic module, and ngx http auth jwt -
module, via the satisfy directive.
location /private/ {
auth_request /auth;
...
}
location = /auth {
proxy_pass ...
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
2.7.3 Directives
auth request
Syntax: auth_request uri | off;
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.
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 *.
2.8.1 Summary
The ngx_http_autoindex_module module processes requests ending
with the slash character (‘/’) and produces a directory listing. Usually a
request is passed to the ngx_http_autoindex_module module when the
ngx http index module module cannot find an index file.
location / {
autoindex on;
}
2.8.3 Directives
autoindex
Syntax: autoindex on | off;
Default off
Context: http, server, location
For the HTML format, specifies whether exact file sizes should be output in
the directory listing, or rather rounded to kilobytes, megabytes, and gigabytes.
autoindex format
Syntax: autoindex_format html | xml | json | jsonp;
Default html
Context: http, server, location
This directive appeared in version 1.7.9.
autoindex localtime
Syntax: autoindex_localtime on | off;
Default off
Context: http, server, location
For the HTML format, specifies whether times in the directory listing
should be output in the local time zone or UTC.
2.9.1 Summary
The ngx_http_browser_module module creates variables whose
values depend on the value of the User-Agent request header field:
$modern browser
equals the value set by the modern browser value directive, if a browser
was identified as modern;
$ancient browser
equals the value set by the ancient browser value directive, if a browser
was identified as ancient;
$msie
equals “1” if a browser was identified as MSIE of any version.
modern_browser_value "modern.";
modern_browser unlisted;
if ($ancient_browser) {
rewrite ^ /ancient.html;
}
2.9.3 Directives
ancient browser
Syntax: ancient_browser string . . . ;
Default —
Context: http, server, location
modern browser
Syntax: modern_browser browser version;
Syntax: modern_browser unlisted;
Default —
Context: http, server, location
2.10.1 Summary
The ngx_http_charset_module module adds the specified charset
to the Content-Type response header field. In addition, the module can
convert data from one charset to another, with some limitations:
include conf/koi-win;
charset windows-1251;
source_charset koi8-r;
2.10.3 Directives
charset
Syntax: charset charset | off;
Default off
Context: http, server, location, if in location
charset $charset;
charset_map iso-8859-5 _ { }
charset map
Syntax: charset_map charset1 charset2 { . . . }
Default —
Context: http
When describing a conversion table to UTF-8, codes for the UTF-8 charset
should be given in the second column, for example:
charset types
Syntax: charset_types mime-type . . . ;
Default text/html text/xml text/plain text/vnd.wap.wml
application/javascript application/rss+xml
Context: http, server, location
This directive appeared in version 0.7.9.
override charset
Syntax: override_charset on | off;
Default off
Context: http, server, location, if in location
source charset
Syntax: source_charset charset;
Default —
Context: http, server, location, if in location
2.11.1 Summary
The ngx_http_dav_module module is intended for file management
automation via the WebDAV protocol. The module processes HTTP and
WebDAV methods PUT, DELETE, MKCOL, COPY, and MOVE.
This module is not built by default, it should be enabled with the
--with-http_dav_module configuration parameter.
location / {
root /data/www;
client_body_temp_path /data/client_temp;
create_full_put_path on;
dav_access group:rw all:r;
limit_except GET {
allow 192.168.1.0/32;
deny all;
}
}
2.11.3 Directives
create full put path
Syntax: create_full_put_path on | off;
Default off
Context: http, server, location
dav access
Syntax: dav_access users:permissions . . . ;
Default user:rw
Context: http, server, location
Sets access permissions for newly created files and directories, e.g.:
dav methods
Syntax: dav_methods 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.
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;
/users/00/00/name
/users/00/00/name/pic.jpg
/users/00/00/page.html
/users/00/00
2.12.1 Summary
The ngx_http_empty_gif_module module emits single-pixel trans-
parent GIF.
location = /_.gif {
empty_gif;
}
2.12.3 Directives
empty gif
Syntax: empty_gif;
Default —
Context: location
2.13.1 Summary
The ngx_http_f4f_module module provides server-side support for
Adobe HTTP Dynamic Streaming (HDS).
This module implements handling of HTTP Dynamic Streaming requests
in the “/videoSeg1-Frag1” form — extracting the needed fragment from
the videoSeg1.f4f file using the videoSeg1.f4x index file. This module
is an alternative to the Adobe’s f4f module (HTTP Origin Module) for Apache.
Usual pre-processing with Adobe’s f4fpackager is required, see relevant
documentation for details.
location /video/ {
f4f;
...
}
2.13.3 Directives
f4f
Syntax: f4f;
Default —
Context: location
Sets the size of the buffer used for reading the .f4x index file.
2.14.1 Summary
The ngx_http_fastcgi_module module allows passing requests to a
FastCGI server.
location / {
fastcgi_pass localhost:9000;
fastcgi_index index.php;
2.14.3 Directives
fastcgi bind
Syntax: fastcgi_bind address [transparent] | off;
Default —
Context: http, server, location
This directive appeared in version 0.8.22.
Sets the size of the buffer used for reading the first part of the response
received from the FastCGI server. This part usually contains a small response
header. By default, the buffer size is equal to one memory page. This is either
4K or 8K, depending on a platform. It can be made smaller, however.
fastcgi buffering
Syntax: fastcgi_buffering on | off;
Default on
Context: http, server, location
This directive appeared in version 1.5.6.
fastcgi buffers
Syntax: fastcgi_buffers number size;
Default 8 4k|8k
Context: http, server, location
Sets the number and size of the 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.
When 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 meantime, the rest of the buffers can be
used for reading the response and, if needed, buffering part of the 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.
fastcgi cache
Syntax: fastcgi_cache zone | off;
Default off
Context: http, server, location
Defines a shared memory zone used for caching. The same zone can be
used in several places. Parameter value can contain variables (1.7.9). The off
parameter disables caching inherited from the previous configuration level.
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_key localhost:9000$request_uri;
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.
If the last request passed to the FastCGI server for populating a new cache
element has not completed for the specified time, one more request may be
passed to the FastCGI server.
Sets a timeout for fastcgi cache lock. When the time expires, the request
will be passed to the FastCGI server, however, the response will not be cached.
Sets an offset in bytes for byte-range requests. If the range is beyond the
offset, the range request will be passed to the FastCGI server and the response
will not be cached.
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.
Sets the number of requests after which the response will be cached.
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: from 1 to 3,
each level accepts values 1 or 2. For example, in the following configuration
/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 are put on the same file system. A directory for temporary files
is set based on the use_temp_path parameter (1.7.10). If this parameter
is omitted or set to the value on, the directory set by the fastcgi temp -
path directive for the given location will be used. If the value is set to off,
temporary files will be put directly in the cache directory.
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. One megabyte zone can store about 8 thousand keys.
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. The data is removed in iterations
configured by manager_files, manager_threshold, and manager_-
sleep parameters (1.11.5). During one iteration no more than manager_-
files items are deleted (by default, 100). The duration of one iteration
is limited by the manager_threshold parameter (by default, 200
milliseconds). Between iterations, a pause configured by the manager_sleep
parameter (by default, 50 milliseconds) is made.
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 also 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.
Additionally, the following parameters are available as part of our
commercial subscription:
purger=on|off
In versions 1.7.3, 1.7.7, and 1.11.10 cache header format has been changed.
Previously cached responses will be considered invalid after upgrading to a
newer nginx version.
Defines conditions under which the request will be considered a cache purge
request. If at least one value of the string parameters is not empty and
is not equal to “0” then the cache entry with a corresponding cache key is
removed. The result of successful operation is indicated by returning the 204
No Content response.
If the cache key of a purge request ends with an asterisk (“*”), all cache
entries matching the wildcard key will be removed from the cache. However,
these entries will remain on the disk until they are deleted for either inactivity,
or processed by the cache purger (1.7.12), or a client attempts to access them.
Example configuration:
server {
...
location / {
fastcgi_pass backend;
fastcgi_cache cache_zone;
fastcgi_cache_key $uri;
fastcgi_cache_purge $purge_method;
}
Sets caching time for different response codes. For example, the following
directives
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;
Parameters of caching can also be set directly in the response header. This
has higher priority than setting of caching time using the directive.
• If the header includes the Set-Cookie field, such a response will not
be cached.
• If the header includes the Vary field with the special value “*”, such a
response will not be cached (1.7.7). If the header includes the Vary field
with another value, such a response will be cached taking into account
the corresponding request header fields (1.7.7).
Processing of one or more of these response header fields can be disabled using
the fastcgi ignore headers directive.
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 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;
}
Enables byte-range support for both cached and uncached responses from
the FastCGI server regardless of the Accept-Ranges field in these responses.
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.
fastcgi index
Syntax: fastcgi_index 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;
Limits the speed of reading the response from the FastCGI server. The
rate is specified in bytes per second. The zero value disables rate limiting. The
limit is set per a request, and so if nginx simultaneously opens two connections
to the FastCFI server, the overall rate will be twice as much as the specified
limit. The limitation works only if buffering of responses from the FastCGI
server is enabled.
When buffering of responses from the FastCGI server is enabled, and the
whole response does not fit into the 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 the temporary file. The size of
data written to the 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.
This restriction does not apply to responses that will be cached or stored
on disk.
error
an error occurred while establishing a connection with the server, passing
a request to it, or reading the response header;
timeout
a timeout has occurred while establishing a connection with the server,
passing a request to it, or reading the response header;
invalid_header
a server returned an empty or invalid response;
http_500
a server returned a response with the code 500;
http_503
a server returned a response with the code 503;
http_403
a server returned a response with the code 403;
http_404
a server returned a response with the code 404;
http_429
a server returned a response with the code 429 (1.11.13);
non_idempotent
normally, requests with a non-idempotent method (POST, LOCK, PATCH)
are not passed to the next server if a request has been sent to an
upstream server (1.9.13); enabling this option explicitly allows retrying
such requests;
off
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_503, and http_-
429 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.
Passing a request to the next server can be limited by the number of tries
and by time.
Limits the time during which a request can be passed to the next server.
The 0 value turns off this limitation.
Limits the number of possible tries for passing a request to the next server.
The 0 value turns off this limitation.
fastcgi no cache
Syntax: fastcgi_no_cache 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 param
Syntax: fastcgi_param parameter value [if_not_empty];
Default —
Context: http, server, location
fastcgi pass
Syntax: fastcgi_pass address;
Default —
Context: location, if in location
fastcgi_pass localhost:9000;
fastcgi_pass unix:/tmp/fastcgi.socket;
Indicates whether the original request body is passed to the FastCGI server.
See also the fastcgi pass request headers directive.
Indicates whether the header fields of the original request are passed to the
FastCGI server. See also the fastcgi pass request body directive.
Defines a timeout for reading a response from the FastCGI server. The
timeout is set only between two successive read operations, not for the
transmission of the whole response. If the FastCGI server does not transmit
anything within this time, the connection is closed.
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.
Defines a regular expression that captures a value for the $fastcgi path info
variable. The 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;
fastcgi store
Syntax: fastcgi_store on | off | 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;
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;
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/;
}
Sets access permissions for newly created files and directories, e.g.:
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.
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;
/spool/nginx/fastcgi_temp/7/45/00000123457
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
2.15.1 Summary
The ngx_http_flv_module module provides pseudo-streaming server-
side support for Flash Video (FLV) files.
It handles requests with the start argument in the request URI’s query
string specially, by sending back the contents of a file starting from the
requested byte offset and with the prepended FLV header.
This module is not built by default, it should be enabled with the
--with-http_flv_module configuration parameter.
location ~ \.flv$ {
flv;
}
2.15.3 Directives
flv
Syntax: flv;
Default —
Context: location
2.16.1 Summary
The ngx_http_geo_module module creates variables with values
depending on the client IP address.
geo $geo {
default 0;
127.0.0.1 2;
192.168.1.0/24 1;
10.1.0.0/16 1;
::1 2;
2001:0db8::/32 1;
}
2.16.3 Directives
geo
Syntax: geo [$address] $variable { . . . }
Default —
Context: http
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.
delete
deletes the specified network (0.7.23).
default
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.
include
includes a file with addresses and values. There can be several inclusions.
proxy
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.
proxy_recursive
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.
ranges
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;
}
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;
}
2.17.1 Summary
The ngx_http_geoip_module module (0.8.6+) creates variables with
values depending on the client IP address, using the precompiled MaxMind
databases.
When using the databases with IPv6 support (1.3.12, 1.2.7), IPv4 addresses
are looked up as IPv4-mapped IPv6 addresses.
This module is not built by default, it should be enabled with the
--with-http_geoip_module configuration parameter.
http {
geoip_country GeoIP.dat;
geoip_city GeoLiteCity.dat;
geoip_proxy 192.168.100.0/24;
geoip_proxy 2001:0db8::/32;
geoip_proxy_recursive on;
...
2.17.3 Directives
geoip country
Syntax: geoip_country file;
Default —
Context: http
geoip city
Syntax: geoip_city file;
Default —
Context: http
geoip org
Syntax: geoip_org file;
Default —
Context: http
This directive appeared in version 1.0.3.
$geoip org
organization name, for example, “The University of Melbourne”.
geoip proxy
Syntax: geoip_proxy address | CIDR;
Default —
Context: http
This directive appeared in versions 1.3.0 and 1.2.1.
2.18.1 Summary
The ngx_http_grpc_module module allows passing requests to a gRPC
server (1.13.10). The module requires the ngx http v2 module module.
server {
listen 9000 http2;
location / {
grpc_pass 127.0.0.1:9000;
}
}
2.18.3 Directives
grpc bind
Syntax: grpc_bind address [transparent ] | off;
Default —
Context: http, server, location
Sets the size of the buffer used for reading the response received from the
gRPC server. The response is passed to the client synchronously, as soon as it
is received.
By default, nginx does not pass the header fields Date, Server, and
X-Accel-... from the response of a gRPC server to a client. The grpc_-
hide_header directive sets additional fields that will not be passed. If, on
the contrary, the passing of fields needs to be permitted, the grpc pass header
directive can be used.
error
an error occurred while establishing a connection with the server, passing
a request to it, or reading the response header;
timeout
a timeout has occurred while establishing a connection with the server,
passing a request to it, or reading the response header;
invalid_header
a server returned an empty or invalid response;
http_500
a server returned a response with the code 500;
http_502
a server returned a response with the code 502;
http_503
a server returned a response with the code 503;
http_504
a server returned a response with the code 504;
http_403
a server returned a response with the code 403;
http_404
a server returned a response with the code 404;
http_429
a server returned a response with the code 429;
non_idempotent
normally, requests with a non-idempotent method (POST, LOCK, PATCH)
are not passed to the next server if a request has been sent to an upstream
server; enabling this option explicitly allows retrying such requests;
off
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,
http_504, and http_429 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.
Passing a request to the next server can be limited by the number of tries
and by time.
Limits the time during which a request can be passed to the next server.
The 0 value turns off this limitation.
Limits the number of possible tries for passing a request to the next server.
The 0 value turns off this limitation.
grpc pass
Syntax: grpc_pass address;
Default —
Context: location, if in location
Sets the gRPC server address. The address can be specified as a domain
name or IP address, and a port:
grpc_pass localhost:9000;
grpc_pass unix:/tmp/grpc.socket;
grpc_pass grpc://127.0.0.1:9000;
grpc_pass grpcs://127.0.0.1:443;
Defines a timeout for reading a response from the gRPC server. The
timeout is set only between two successive read operations, not for the
transmission of the whole response. If the gRPC server does not transmit
anything within this time, the connection is closed.
Sets a timeout for transmitting a request to the gRPC server. The timeout
is set only between two successive write operations, not for the transmission
of the whole request. If the gRPC server does not receive anything within this
time, the connection is closed.
Specifies a file with the certificate in the PEM format used for
authentication to a gRPC SSL server.
Specifies a file with the secret key in the PEM format used for
authentication to a gRPC SSL server.
The value engine:name:id can be specified instead of the file, which loads
a secret key with a specified id from the OpenSSL engine name.
Specifies the enabled ciphers for requests to a gRPC SSL server. The
ciphers are specified in the format understood by the OpenSSL library.
The full list can be viewed using the “openssl ciphers” command.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify the certificate of the gRPC SSL server.
Allows overriding the server name used to verify the certificate of the gRPC
SSL server and to be passed through SNI when establishing a connection with
the gRPC SSL server.
By default, the host part from grpc pass is used.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Enables or disables passing of the server name through TLS Server Name
Indication extension (SNI, RFC 6066) when establishing a connection with the
gRPC SSL server.
Sets the verification depth in the gRPC SSL server certificates chain.
2.19.1 Summary
The ngx_http_gunzip_module module is a filter that decompresses
responses with “Content-Encoding: gzip” for clients that do not
support “gzip” encoding method. The module will be useful when it is desirable
to store data compressed to save space and reduce I/O costs.
This module is not built by default, it should be enabled with the
--with-http_gunzip_module configuration parameter.
location /storage/ {
gunzip on;
...
}
2.19.3 Directives
gunzip
Syntax: gunzip on | off;
Default off
Context: http, server, location
gunzip buffers
Syntax: gunzip_buffers number size;
Default 32 4k|16 8k
Context: http, server, location
2.20.1 Summary
The ngx_http_gzip_module module is a filter that compresses
responses using the “gzip” method. This often helps to reduce the size of
transmitted data by half or even more.
gzip on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain application/xml;
The $gzip ratio variable can be used to log the achieved compression ratio.
2.20.3 Directives
gzip
Syntax: gzip on | off;
Default off
Context: http, server, location, if in location
gzip buffers
Syntax: gzip_buffers 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.
gzip disable
Syntax: gzip_disable regex . . . ;
Default —
Context: http, server, location
This directive appeared in version 0.6.23.
Sets the minimum length of a response that will be gzipped. The length is
determined only from the Content-Length response header field.
gzip proxied
Syntax: gzip_proxied off | expired | no-cache | no-store | private |
no_last_modified | no_etag | auth | any . . . ;
Default off
Context: http, server, location
off
disables compression for all proxied requests, ignoring other parameters;
expired
enables compression if a response header includes the Expires field
with a value that disables caching;
no-cache
enables compression if a response header includes the Cache-Control
field with the “no-cache” parameter;
no-store
enables compression if a response header includes the Cache-Control
field with the “no-store” parameter;
private
enables compression if a response header includes the Cache-Control
field with the “private” parameter;
no_last_modified
enables compression if a response header does not include the
Last-Modified field;
no_etag
enables compression if a response header does not include the ETag field;
auth
enables compression if a request header includes the Authorization
field;
any
enables compression for all proxied requests.
gzip types
Syntax: gzip_types mime-type . . . ;
Default text/html
Context: http, server, location
gzip vary
Syntax: gzip_vary on | off;
Default off
Context: http, server, location
2.21.1 Summary
The ngx_http_gzip_static_module module allows sending precom-
pressed files with the “.gz” filename extension instead of regular files.
This module is not built by default, it should be enabled with the
--with-http_gzip_static_module configuration parameter.
gzip_static on;
gzip_proxied expired no-cache no-store private auth;
2.21.3 Directives
gzip static
Syntax: gzip_static on | off | always;
Default off
Context: http, server, location
2.22.1 Summary
The ngx_http_headers_module module allows adding the Expires
and Cache-Control header fields, and arbitrary fields, to a response header.
expires 24h;
expires modified +24h;
expires @24h;
expires 0;
expires -1;
expires epoch;
expires $expires;
add_header Cache-Control private;
2.22.3 Directives
add header
Syntax: add_header name value [always];
Default —
Context: http, server, location, if in location
Adds the specified field to a response header provided that the response
code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13),
or 308 (1.13.0). The value can contain variables.
There could be several add_header directives. These directives are
inherited from the previous level if and only if there are no add_header
directives defined on the current level.
If the always parameter is specified (1.7.5), the header field will be added
regardless of the response code.
add trailer
Syntax: add_trailer name value [always];
Default —
Context: http, server, location, if in location
This directive appeared in version 1.13.2.
Adds the specified field to the end of a response provided that the response
code equals 200, 201, 206, 301, 302, 303, 307, or 308. The value can contain
variables.
There could be several add_trailer directives. These directives are
inherited from the previous level if and only if there are no add_trailer
directives defined on the current level.
If the always parameter is specified the specified field will be added
regardless of the response code.
expires
Syntax: expires [modified] time;
Syntax: expires epoch | max | off;
Default off
Context: http, server, location, if in location
expires @15h30m;
expires $expires;
2.23.1 Summary
The ngx_http_hls_module module provides HTTP Live Streaming
(HLS) server-side support for MP4 and MOV media files. Such files typically
have the .mp4, .m4v, .m4a, .mov, or .qt filename extensions. The module
supports H.264 video codec, AAC and MP3 audio codecs.
For each media file, two URIs are supported:
• A fragment URI with the “.ts” filename extension. The URI can accept
optional arguments:
location / {
hls;
hls_fragment 5s;
hls_buffers 10 10m;
hls_mp4_buffer_size 1m;
hls_mp4_max_buffer_size 5m;
root /var/video/;
}
With this configuration, the following URIs are supported for the “/var¬
/video/test.mp4” file:
http://hls.example.com/test.mp4.m3u8?offset=1.000&start=1.000&end=2.200
http://hls.example.com/test.mp4.m3u8?len=8.000
http://hls.example.com/test.mp4.ts?start=1.000&end=2.200
2.23.3 Directives
hls
Syntax: hls;
Default —
Context: location
hls buffers
Syntax: hls_buffers 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.
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:15
#EXT-X-PLAYLIST-TYPE:VOD
#EXTINF:9.333,
test.mp4.ts?start=0.000&end=9.333&a=1&b=2
#EXTINF:7.167,
test.mp4.ts?start=9.333&end=16.500&a=1&b=2
#EXTINF:5.416,
test.mp4.ts?start=16.500&end=21.916&a=1&b=2
#EXTINF:5.500,
test.mp4.ts?start=21.916&end=27.416&a=1&b=2
#EXTINF:15.167,
test.mp4.ts?start=27.416&end=42.583&a=1&b=2
#EXTINF:9.626,
test.mp4.ts?start=42.583&end=52.209&a=1&b=2
#EXT-X-ENDLIST
If an HLS stream is protected with the ngx http secure link module
module, $uri should not be used in the secure link md5 expression because
this will cause errors when requesting the fragments. Base URI should be used
instead of $uri ($hls uri in the example):
http {
...
server {
...
location /hls/ {
hls;
hls_forward_args on;
alias /var/videos/;
secure_link $arg_md5,$arg_expires;
secure_link_md5 "$secure_link_expires$hls_uri$remote_addr secret";
if ($secure_link = "") {
return 403;
}
if ($secure_link = "0") {
return 410;
}
}
}
}
hls fragment
Syntax: hls_fragment time;
Default 5s
Context: http, server, location
Defines the default fragment length for playlist URIs requested without the
“len” argument.
Sets the initial size of the buffer used for processing MP4 and MOV files.
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:
2.24.1 Summary
The ngx_http_image_filter_module module (0.7.54+) is a filter
that transforms images in JPEG, GIF, PNG, and WebP formats.
This module is not built by default, it should be enabled with the
--with-http_image_filter_module configuration parameter.
This module utilizes the libgd library. It is recommended to use the latest
available version of the library.
location /img/ {
proxy_pass http://backend;
image_filter resize 150 100;
image_filter rotate 90;
error_page 415 = /empty;
}
location = /empty {
empty_gif;
}
2.24.3 Directives
image filter
Syntax: image_filter off;
Syntax: image_filter test;
Syntax: image_filter size;
Syntax: image_filter rotate 90 | 180 | 270;
Syntax: image_filter resize width height;
Syntax: image_filter crop width height;
Default off
Context: location
off
turns off module processing in a surrounding location.
test
ensures that responses are images in either JPEG, GIF, PNG, or WebP
format. Otherwise, the 415 Unsupported Media Type error is
returned.
size
outputs information about images in a JSON format, e.g.:
{}
rotate 90|180|270
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.
resize 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.
crop 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.
Sets the maximum size of the buffer used for reading images. When the
size is exceeded the server returns error 415 Unsupported Media Type.
If enabled, final images will be interlaced. For JPEG, final images will be
in “progressive JPEG” format.
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.
Sets the desired quality of the transformed WebP images. Acceptable values
are in the range from 1 to 100. Lesser values usually imply both lower image
quality and less data to transfer. Parameter value can contain variables.
2.25.1 Summary
The ngx_http_index_module module processes requests ending with
the slash character (‘/’). Such requests can also be processed by the ngx -
http autoindex module and ngx http random index module modules.
location / {
index index.$geo.html index.html;
}
2.25.3 Directives
index
Syntax: index 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:
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 / {
...
}
2.26.1 Summary
The ngx_http_js_module module is used to implement location and
variable handlers in njs — a subset of the JavaScript language.
This module is not built by default. Download and install instructions are
available here.
load_module modules/ngx_http_js_module.so;
...
http {
js_include http.js;
server {
listen 8000;
location / {
add_header X-Foo $foo;
js_content baz;
}
location = /summary {
return 200 $summary;
}
location = /hello {
js_content hello;
}
}
}
function foo(r) {
r.log("hello from foo() handler");
return "foo";
}
function summary(r) {
var a, s, h;
s = "JS summary\n\n";
s += "Headers:\n";
for (h in r.headersIn) {
s += " header ’" + h + "’ is ’" + r.headersIn[h] + "’\n";
}
s += "Args:\n";
for (a in r.args) {
s += " arg ’" + a + "’ is ’" + r.args[a] + "’\n";
}
return s;
}
function baz(r) {
r.status = 200;
r.headersOut.foo = 1234;
r.headersOut[’Content-Type’] = "text/plain; charset=utf-8";
r.headersOut[’Content-Length’] = 15;
r.sendHeader();
r.send("nginx");
r.send("java");
r.send("script");
r.finish();
}
function hello(r) {
r.return(200, "Hello world!");
}
2.26.3 Directives
js content
Syntax: js_content function;
Default —
Context: location, limit except
js include
Syntax: js_include file;
Default —
Context: http
js set
Syntax: js_set $variable function;
Default —
Context: http
2.27.1 Summary
The ngx_http_keyval_module module (1.13.3) creates variables with
values taken from key-value pairs managed by the API.
http {
location /api {
api write=on;
}
}
}
2.27.3 Directives
keyval
Syntax: keyval key $variable zone=name;
Default —
Context: http
Creates a new $variable whose value is looked up by the key in the key-
value database. Strings are matched ignoring the case. The database is stored
in a shared memory zone specified by the zone parameter.
keyval zone
Syntax: keyval_zone zone=name:size [state=file] [timeout=time] [sync];
Default —
Context: http
Sets the name and size of the shared memory zone that keeps the key-value
database. Key-value pairs are managed by the API.
The optional state parameter specifies a file that keeps the current state
of the key-value database in the JSON format and makes it persistent across
nginx restarts.
The optional timeout parameter (1.15.0) sets the time after which key-
value pairs are removed from the zone.
The optional sync parameter (1.15.0) enables synchronization of the
shared memory zone. The synchronization requires the timeout parameter
to be set.
2.28.1 Summary
The ngx_http_limit_conn_module module is used to limit the
number of connections per the defined key, in particular, the number of
connections from a single IP address.
Not all connections are counted. A connection is counted only if it has a
request being processed by the server and the whole request header has already
been read.
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
...
server {
...
location /download/ {
limit_conn addr 1;
}
2.28.3 Directives
limit conn
Syntax: limit_conn 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 error in reply to a request. For example, the directives
server {
location /download/ {
limit_conn addr 1;
}
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.
Sets the desired logging level for cases when the server limits the number
of connections.
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 can contain text, variables, and their combination. Requests with an empty
key value are not accounted.
Usage example:
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 for IPv4 addresses or 16
bytes for IPv6 addresses. The stored state always occupies 32 or 64 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 error to all further
requests.
limit zone
Syntax: limit_zone name $variable size;
Default —
Context: http
This directive was made obsolete in version 1.1.8 and was removed in
version 1.7.6. An equivalent limit conn zone directive with a changed syntax
should be used instead:
2.29.1 Summary
The ngx_http_limit_req_module module (0.7.21) is used to limit
the request processing rate per a defined key, in particular, the processing rate
of requests coming from a single IP address. The limitation is done using the
“leaky bucket” method.
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
...
server {
...
location /search/ {
limit_req zone=one burst=5;
}
2.29.3 Directives
limit req
Syntax: limit_req 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. By default, the maximum burst size
is equal to zero. For example, the directives
server {
location /search/ {
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:
server {
...
limit_req zone=perip burst=5 nodelay;
limit_req zone=perserver burst=10;
}
These directives are inherited from the previous level if and only if there
are no limit_req directives on the current level.
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.
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 can contain text, variables, and their combination. Requests with an
empty key value are not accounted.
Usage example:
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. The $binary remote addr variable’s
size is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses. The
stored state always occupies 64 bytes on 32-bit platforms and 128 bytes on 64-
bit platforms. One megabyte zone can keep about 16 thousand 64-byte states
or about 8 thousand 128-byte states.
If the zone storage is exhausted, the least recently used state is removed.
Even if after that a new state cannot be created, the request is terminated
with an error.
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.
The sync parameter (1.15.3) enables synchronization of the shared
memory zone.
2.30.1 Summary
The ngx_http_log_module module writes request logs in the specified
format.
Requests are logged in the context of a location where processing ends.
It may be different from the original location, if an internal redirect happens
during request processing.
2.30.3 Directives
access log
Syntax: access_log path [format [buffer=size] [gzip[=level]]
[flush=time] [if=condition]];
Syntax: access_log 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.
• 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:
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 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;
...
log format
Syntax: log_format name [escape=default|json|none] string . . . ;
Default combined "..."
Context: http
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:
’"$http_referer" "$http_user_agent"’;
Defines a cache that stores the file descriptors of frequently used logs whose
names contain variables. The directive has the following parameters:
max
sets the maximum number of descriptors in a cache; if the cache becomes
full the least recently used (LRU) descriptors are closed
inactive
sets the time after which the cached descriptor is closed if there were no
access during this time; by default, 10 seconds
min_uses
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
valid
sets the time after which it should be checked that the file still exists
with the same name; by default, 60 seconds
off
disables caching
Usage example:
2.31.1 Summary
The ngx_http_map_module module creates variables whose values
depend on values of other variables.
default 0;
example.com 1;
*.example.com 1;
example.org 2;
*.example.org 2;
.example.net 3;
wap.* 4;
}
2.31.3 Directives
map
Syntax: map string $variable { . . . }
Default —
Context: http
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).
Strings are matched ignoring the case.
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 contain text, variable (0.9.0), and their combination
(1.11.0).
The following special parameters are also supported:
default 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.
hostnames
indicates that source values can be hostnames with a prefix or suffix
mask:
*.example.com 1;
example.* 1;
example.com 1;
*.example.com 1;
can be combined:
.example.com 1;
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:
5. default value
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.
Sets the maximum size of the map variables hash tables. The details of
setting up hash tables are provided in a separate document.
2.32.1 Summary
The ngx_http_memcached_module module is used to obtain responses
from a memcached server. The key is set in the $memcached key variable. A
response should be put in memcached in advance by means external to nginx.
server {
location / {
set $memcached_key "$uri?$args";
memcached_pass host:11211;
error_page 404 502 504 = @fallback;
}
location @fallback {
proxy_pass http://backend;
}
}
2.32.3 Directives
memcached bind
Syntax: memcached_bind address [transparent ] | off;
Default —
Context: http, server, location
This directive appeared in version 0.8.22.
Sets the size of the buffer used for reading the response received from the
memcached server. The response is passed to the client synchronously, as soon
as it is received.
Enables byte-range support for both cached and uncached responses from
the memcached server regardless of the Accept-Ranges field in these
responses.
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
an error occurred while establishing a connection with the server, passing
a request to it, or reading the response header;
timeout
a timeout has occurred while establishing a connection with the server,
passing a request to it, or reading the response header;
invalid_response
a server returned an empty or invalid response;
not_found
a response was not found on the server;
off
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_-
response 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.
Passing a request to the next server can be limited by the number of tries
and by time.
Limits the time during which a request can be passed to the next server.
The 0 value turns off this limitation.
Limits the number of possible tries for passing a request to the next server.
The 0 value turns off this limitation.
memcached pass
Syntax: memcached_pass address;
Default —
Context: location, if in location
memcached_pass localhost:11211;
memcached_pass unix:/tmp/memcached.socket;
2.33.1 Summary
The ngx_http_mirror_module module (1.13.4) implements mirroring
of an original request by creating background mirror subrequests. Responses
to mirror subrequests are ignored.
location / {
mirror /mirror;
proxy_pass http://backend;
}
location = /mirror {
internal;
proxy_pass http://test_backend$request_uri;
}
2.33.3 Directives
mirror
Syntax: mirror uri | off;
Default off
Context: http, server, location
Sets the URI to which an original request will be mirrored. Several mirrors
can be specified on the same level.
location / {
mirror /mirror;
mirror_request_body off;
proxy_pass http://backend;
}
location = /mirror {
internal;
proxy_pass http://log_backend;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
2.34.1 Summary
The ngx_http_mp4_module module provides pseudo-streaming server-
side support for MP4 files. Such files typically have the .mp4, .m4v, or .m4a
filename extensions.
Pseudo-streaming works in alliance with a compatible Flash player. The
player sends an HTTP request to the server with the start time specified in the
query string argument (named simply start and specified in seconds), and
the server responds with the stream such that its start position corresponds to
the requested time, for example:
http://example.com/elephants_dream.mp4?start=238.88
http://example.com/elephants_dream.mp4?start=238.88&end=555.55
location /video/ {
mp4;
mp4_buffer_size 1m;
mp4_max_buffer_size 5m;
mp4_limit_rate on;
mp4_limit_rate_after 30s;
}
2.34.3 Directives
mp4
Syntax: mp4;
Default —
Context: location
Sets the initial size of the buffer used for processing MP4 files.
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:
Sets the initial amount of media data (measured in playback time) after
which the further transmission of the response to a client will be rate limited.
2.35.1 Summary
The ngx_http_perl_module module is used to implement location and
variable handlers in Perl and insert Perl calls into SSI.
This module is not built by default, it should be enabled with the
--with-http_perl_module configuration parameter.
This module requires Perl version 5.6.1 or higher. The C compiler should
be compatible with the one used to build Perl.
http {
perl_modules perl/lib;
perl_require hello.pm;
perl_set $msie6 ’
sub {
my $r = shift;
my $ua = $r->header_in("User-Agent");
’;
server {
location / {
perl hello::handler;
}
}
package hello;
use nginx;
sub handler {
my $r = shift;
$r->send_http_header("text/html");
return OK if $r->header_only;
$r->print("hello!\n<br/>");
if (-f $r->filename or -d _) {
$r->print($r->uri, " exists!\n");
}
return OK;
}
1;
__END__
2.35.4 Directives
perl
Syntax: perl module::function|’sub { . . . }’;
Default —
Context: location, limit except
perl modules
Syntax: perl_modules path;
Default —
Context: http
perl require
Syntax: perl_require module;
Default —
Context: http
perl set
Syntax: perl_set $variable module::function|’sub { . . . }’;
Default —
Context: http
package hello;
use nginx;
sub handler {
my $r = shift;
if ($r->request_method ne "POST") {
return DECLINED;
}
if ($r->has_request_body(\&post)) {
return OK;
}
return HTTP_BAD_REQUEST;
}
sub post {
my $r = shift;
$r->send_http_header;
return OK;
}
1;
__END__
$r->allow_ranges
enables the use of byte ranges when sending responses.
$r->discard_request_body
instructs nginx to discard the request body.
$r->header_in(field)
returns the value of the specified client request header field.
$r->header_only
determines whether the whole response or only its header should be sent
to the client.
$r->header_out(field, value)
sets a value for the specified response header field.
$r->internal_redirect(uri)
does an internal redirect to the specified uri. An actual redirect happens
after the Perl handler execution is completed.
$r->log_error(errno, message)
writes the specified message into the error log. If errno is non-zero, an
error code and its description will be appended to the message.
$r->print(text, ...)
passes data to a client.
$r->request_body
returns the client request body if it has not been written to a temporary
file. To ensure that the client request body is in memory, its size should
be limited by client max body size, and a sufficient buffer size should be
set using client body buffer size.
$r->request_body_file
returns the name of the file with the client request body. After the
processing, the file should be removed. To always write a request body
to a file, client body in file only should be enabled.
$r->request_method
returns the client request HTTP method.
$r->remote_addr
returns the client IP address.
$r->flush
immediately sends data to the client.
$r->sendfile(name[, offset[, length]])
sends the specified file content to the client. Optional parameters specify
the initial offset and length of the data to be transmitted. The actual
data transmission happens after the Perl handler has completed.
$r->send_http_header([type])
sends the response header to the client. The optional type parameter sets
the value of the Content-Type response header field. If the value is
an empty string, the Content-Type header field will not be sent.
$r->status(code)
sets a response code.
$r->sleep(milliseconds, handler)
sets the specified handler and stops request processing for the specified
time. In the meantime, nginx continues to process other requests. After
the specified time has elapsed, nginx will call the installed handler. Note
that the handler function should be passed by reference. In order to pass
data between handlers, $r->variable() should be used. Example:
package hello;
use nginx;
sub handler {
my $r = shift;
$r->discard_request_body;
$r->variable("var", "OK");
$r->sleep(1000, \&next);
return OK;
}
sub next {
my $r = shift;
$r->send_http_header;
$r->print($r->variable("var"));
return OK;
}
1;
__END__
$r->unescape(text)
decodes a text encoded in the “%XX” form.
$r->uri
returns a request URI.
$r->variable(name[, value])
returns or sets the value of the specified variable. Variables are local to
each request.
2.36.1 Summary
The ngx_http_proxy_module module allows passing requests to
another server.
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
2.36.3 Directives
proxy bind
Syntax: proxy_bind address [transparent] | off;
Default —
Context: http, server, location
Sets the size of the buffer used for reading the first part of the response
received from the proxied server. This part usually contains a small response
header. By default, the buffer size is equal to one memory page. This is either
4K or 8K, depending on a platform. It can be made smaller, however.
proxy buffering
Syntax: proxy_buffering on | off;
Default on
Context: http, server, location
proxy buffers
Syntax: proxy_buffers number size;
Default 8 4k|8k
Context: http, server, location
Sets the number and size of the 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.
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 meantime, the rest of the buffers can be
used for reading the response and, if needed, buffering part of the 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.
proxy cache
Syntax: proxy_cache zone | off;
Default off
Context: http, server, location
Defines a shared memory zone used for caching. The same zone can be
used in several places. Parameter value can contain variables (1.7.9). The off
parameter disables caching inherited from the previous configuration level.
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_key $scheme$proxy_host$uri$is_args$args;
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.
If the last request passed to the proxied server for populating a new cache
element has not completed for the specified time, one more request may be
passed to the proxied server.
Sets a timeout for proxy cache lock. When the time expires, the request
will be passed to the proxied server, however, the response will not be cached.
Sets an offset in bytes for byte-range requests. If the range is beyond the
offset, the range request will be passed to the proxied server and the response
will not be cached.
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.
Sets the number of requests after which the response will be cached.
Sets the path and other parameters of a cache. Cache data are stored in
files. The file name in a cache is a result of applying the MD5 function to
the cache key. The levels parameter defines hierarchy levels of a cache:
from 1 to 3, each level accepts values 1 or 2. For example, in the following
configuration
/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 are put on the same file system. The directory for
temporary files is set based on the use_temp_path parameter (1.7.10). If
this parameter is omitted or set to the value on, the directory set by the
proxy temp path directive for the given location will be used. If the value is
set to off, temporary files will be put directly in the cache directory.
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. One megabyte zone can store about 8 thousand keys.
for the same number of keys. For example, one megabyte zone can store
about 4 thousand keys.
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. The data is removed in iterations
configured by manager_files, manager_threshold, and manager_-
sleep parameters (1.11.5). During one iteration no more than manager_-
files items are deleted (by default, 100). The duration of one iteration
is limited by the manager_threshold parameter (by default, 200
milliseconds). Between iterations, a pause configured by the manager_sleep
parameter (by default, 50 milliseconds) is made.
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 also 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.
Additionally, the following parameters are available as part of our
commercial subscription:
purger=on|off
Instructs whether cache entries that match a wildcard key will be
removed from the disk by the cache purger (1.7.12). Setting the
parameter to on (default is off) will activate the “cache purger” process
that permanently iterates through all cache entries and deletes the entries
that match the wildcard key.
purger_files=number
Sets the number of items that will be scanned during one iteration
(1.7.12). By default, purger_files is set to 10.
purger_threshold=number
Sets the duration of one iteration (1.7.12). By default, purger_-
threshold is set to 50 milliseconds.
purger_sleep=number
Sets a pause between iterations (1.7.12). By default, purger_sleep is
set to 50 milliseconds.
In versions 1.7.3, 1.7.7, and 1.11.10 cache header format has been changed.
Previously cached responses will be considered invalid after upgrading to a
newer nginx version.
Defines conditions under which the request will be considered a cache purge
request. If at least one value of the string parameters is not empty and
is not equal to “0” then the cache entry with a corresponding cache key is
removed. The result of successful operation is indicated by returning the 204
No Content response.
If the cache key of a purge request ends with an asterisk (“*”), all cache
entries matching the wildcard key will be removed from the cache. However,
these entries will remain on the disk until they are deleted for either inactivity,
or processed by the cache purger (1.7.12), or a client attempts to access them.
Example configuration:
server {
...
location / {
proxy_pass http://backend;
proxy_cache cache_zone;
proxy_cache_key $uri;
proxy_cache_purge $purge_method;
}
}
Sets caching time for different response codes. For example, the following
directives
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;
Parameters of caching can also be set directly in the response header. This
has higher priority than setting of caching time using the directive.
• If the header includes the Set-Cookie field, such a response will not
be cached.
• If the header includes the Vary field with the special value “*”, such a
response will not be cached (1.7.7). If the header includes the Vary field
with another value, such a response will be cached taking into account
the corresponding request header fields (1.7.7).
Processing of one or more of these response header fields can be disabled using
the proxy ignore headers directive.
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 off;
proxy_cookie_domain localhost example.org;
proxy_cookie_domain www.example.org example.org;
proxy_cookie_path /two/ /;
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. The regular expression
can contain named and positional captures, and replacement can reference
them:
proxy_cookie_path /one/ /;
proxy_cookie_path / /two/;
proxy_cookie_path off;
proxy_cookie_path /two/ /;
proxy_cookie_path ~*^/user/([^/]+) /u/$1;
Enables byte-range support for both cached and uncached responses from
the proxied server regardless of the Accept-Ranges field in these responses.
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.
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.
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.
Sets the HTTP protocol version for proxying. By default, version 1.0 is
used. Version 1.1 is recommended for use with keepalive connections and
NTLM authentication.
Limits the speed of reading the response from the proxied server. The rate
is specified in bytes per second. The zero value disables rate limiting. The limit
is set per a request, and so if nginx simultaneously opens two connections to
the proxied server, the overall rate will be twice as much as the specified limit.
The limitation works only if buffering of responses from the proxied server is
enabled.
When buffering of responses from the proxied server is enabled, and the
whole response does not fit into the 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 the temporary file. The size of data
written to the 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.
This restriction does not apply to responses that will be cached or stored
on disk.
proxy method
Syntax: proxy_method method;
Default —
Context: http, server, location
are specified in the directive. The cases of http_403 and http_404 are
never considered unsuccessful attempts.
Passing a request to the next server can be limited by the number of tries
and by time.
Limits the time during which a request can be passed to the next server.
The 0 value turns off this limitation.
Limits the number of possible tries for passing a request to the next server.
The 0 value turns off this limitation.
proxy no cache
Syntax: proxy_no_cache 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 pass
Syntax: proxy_pass 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/;
proxy_pass http://unix:/tmp/backend.socket:/uri/;
location /name/ {
proxy_pass http://127.0.0.1/remote/;
}
location /some/path/ {
proxy_pass http://127.0.0.1;
}
• 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.
location /name/ {
proxy_pass http://127.0.0.1$request_uri;
}
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.
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.
Defines a timeout for reading a response from the proxied server. The
timeout is set only between two successive read operations, not for the
transmission of the whole response. If the proxied server does not transmit
anything within this time, the connection is closed.
proxy redirect
Syntax: proxy_redirect default;
Syntax: proxy_redirect off;
Syntax: proxy_redirect 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/ /;
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/;
proxy_redirect http://$proxy_host:8000/ /;
proxy_redirect default;
proxy_redirect http://localhost:8000/ /;
proxy_redirect http://www.example.com/ /;
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 / /;
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.
Sets a timeout for transmitting a request to the proxied server. The timeout
is set only between two successive write operations, not for the transmission of
the whole request. If the proxied server does not receive anything within this
time, the connection is closed.
Allows redefining the request body passed to the proxied server. The value
can contain text, variables, and their combination.
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:
In addition, the server name can be passed together with the port of the
proxied server:
If the value of a header field is an empty string then this field will not be
passed to a proxied server:
Specifies a file with the certificate in the PEM format used for
authentication to a proxied HTTPS server.
Specifies a file with the secret key in the PEM format used for
authentication to a proxied HTTPS server.
The value engine:name:id can be specified instead of the file (1.7.9), which
loads a secret key with a specified id from the OpenSSL engine name.
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.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify the certificate of the proxied HTTPS server.
Allows overriding the server name used to verify the certificate of the
proxied HTTPS server and to be passed through SNI when establishing a
connection with the proxied HTTPS server.
By default, the host part of the proxy pass URL is used.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Enables or disables passing of the server name through TLS Server Name
Indication extension (SNI, RFC 6066) when establishing a connection with the
proxied HTTPS server.
Sets the verification depth in the proxied HTTPS server certificates chain.
proxy store
Syntax: proxy_store on | off | 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;
location /images/ {
root /data/www;
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;
}
Sets access permissions for newly created files and directories, e.g.:
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.
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;
/spool/nginx/proxy_temp/7/45/00000123457
$proxy host
name and port of a proxied server as specified in the proxy pass directive;
$proxy port
port of a proxied server as specified in the proxy pass directive, or the
protocol’s default port;
$proxy add x forwarded for
the X-Forwarded-For client request header field with the
$remote addr variable appended to it, separated by a comma. If the
X-Forwarded-For field is not present in the client request header, the
$proxy add x forwarded for variable is equal to the $remote addr vari-
able.
2.37.1 Summary
The ngx_http_random_index_module module processes requests
ending with the slash character (‘/’) and picks a random file in a directory
to serve as an index file. The module is processed before the ngx http index -
module module.
This module is not built by default, it should be enabled with the
--with-http_random_index_module configuration parameter.
location / {
random_index on;
}
2.37.3 Directives
random index
Syntax: random_index on | off;
Default off
Context: location
2.38.1 Summary
The ngx_http_realip_module module is used to change the client
address and optional port to those sent in the specified header field.
This module is not built by default, it should be enabled with the
--with-http_realip_module configuration parameter.
set_real_ip_from 192.168.1.0/24;
set_real_ip_from 192.168.2.1;
set_real_ip_from 2001:0db8::/32;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
2.38.3 Directives
set real ip from
Syntax: set_real_ip_from address | CIDR | unix:;
Default —
Context: http, server, location
IPv6 addresses are supported starting from versions 1.3.0 and 1.2.1.
real ip header
Syntax: real_ip_header field | X-Real-IP | X-Forwarded-For |
proxy_protocol;
Default X-Real-IP
Context: http, server, location
Defines the request header field whose value will be used to replace the
client address.
The request header field value that contains an optional port is also used
to replace the client port (1.11.0). The address and port should be specified
according to RFC 3986.
The proxy_protocol parameter (1.5.12) changes the client address to
the one from the PROXY protocol header. The PROXY protocol must be
previously enabled by setting the proxy_protocol parameter in the listen
directive.
real ip recursive
Syntax: real_ip_recursive on | off;
Default off
Context: http, server, location
This directive appeared in versions 1.3.0 and 1.2.1.
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.
2.39.1 Summary
The ngx_http_referer_module module is used to block access to a
site for requests with invalid values in the Referer header field. It should
be kept in mind that fabricating a request with an appropriate Referer field
value is quite easy, and so the intended purpose of this module is not to block
such requests thoroughly but to block the mass flow of requests sent by regular
browsers. It should also be taken into consideration that regular browsers may
not send the Referer field even for valid requests.
if ($invalid_referer) {
return 403;
}
2.39.3 Directives
referer hash bucket size
Syntax: referer_hash_bucket_size size;
Default 64
Context: server, location
This directive appeared in version 1.0.5.
Sets the bucket size for the valid referers hash tables. The details of setting
up hash tables are provided in a separate document.
Sets the maximum size of the valid referers hash tables. The details of
setting up hash tables are provided in a separate document.
valid referers
Syntax: valid_referers none | blocked | server_names | 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:
none
the Referer field is missing in the request header;
blocked
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://”;
server_names
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:
2.40.1 Summary
The ngx_http_rewrite_module module is used to change request URI
using PCRE regular expressions, return redirects, and conditionally select
configurations.
The break, if, return, rewrite, and set directives are processed in the
following order:
• the directives of this module specified on the server level are executed
sequentially;
• repeatedly:
2.40.2 Directives
break
Syntax: break;
Default —
Context: server, location, if
if ($slow) {
limit_rate 10k;
break;
}
if
Syntax: if (condition) { . . . }
Default —
Context: server, location
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, 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;
}
return
Syntax: return code [text];
Syntax: return code URL;
Syntax: return 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, 307, and 308) 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.
The code 308 was not treated as a redirect until version 1.13.0.
rewrite
Syntax: rewrite regex replacement [flag];
Default —
Context: server, location, if
last
stops processing the current set of ngx_http_rewrite_module
directives and starts a search for a new location matching the changed
URI;
break
stops processing the current set of ngx_http_rewrite_module
directives as with the break directive;
redirect
returns a temporary redirect with the 302 code; used if a replacement
string does not start with “http://”, “https://”, or “$scheme”;
permanent
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;
}
rewrite log
Syntax: rewrite_log on | off;
Default off
Context: http, server, location, if
set
Syntax: set $variable value;
Default —
Context: server, location, if
Sets a value for the specified variable. The value can contain text, variables,
and their combination.
location /download/ {
if ($forbidden) {
return 403;
}
if ($slow) {
limit_rate 10k;
}
variable $forbidden
check against zero
return 403
end of code
variable $slow
check against zero
match of regular expression
copy "/"
copy $1
copy "/mp3/"
copy $2
copy ".mp3"
end of regular expression
end of code
Note that there are no instructions for the limit rate directive above as
it is unrelated to the ngx_http_rewrite_module module. A separate
configuration is created for the if block. If the condition holds true, a request
is assigned this configuration where limit_rate equals to 10k.
The directive
can be made smaller by one instruction if the first slash in the regular
expression is put inside the parentheses:
2.41.1 Summary
The ngx_http_scgi_module module allows passing requests to an
SCGI server.
location / {
include scgi_params;
scgi_pass localhost:9000;
}
2.41.3 Directives
scgi bind
Syntax: scgi_bind address [transparent] | off;
Default —
Context: http, server, location
Sets the size of the buffer used for reading the first part of the response
received from the SCGI server. This part usually contains a small response
header. By default, the buffer size is equal to one memory page. This is either
4K or 8K, depending on a platform. It can be made smaller, however.
scgi buffering
Syntax: scgi_buffering on | off;
Default on
Context: http, server, location
scgi buffers
Syntax: scgi_buffers number size;
Default 8 4k|8k
Context: http, server, location
Sets the number and size of the buffers used for reading a response from
the SCGI 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.
When buffering of responses from the SCGI 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 meantime, the rest of the buffers can be
used for reading the response and, if needed, buffering part of the response to
a temporary file. By default, size is limited by the size of two buffers set by
the scgi buffer size and scgi buffers directives.
scgi cache
Syntax: scgi_cache zone | off;
Default off
Context: http, server, location
Defines a shared memory zone used for caching. The same zone can be
used in several places. Parameter value can contain variables (1.7.9). The off
parameter disables caching inherited from the previous configuration level.
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:
scgi_cache_key localhost:9000$request_uri;
When enabled, only one request at a time will be allowed to populate a new
cache element identified according to the scgi cache key directive by passing a
request to an SCGI 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 scgi cache lock timeout directive.
If the last request passed to the SCGI server for populating a new cache
element has not completed for the specified time, one more request may be
passed to the SCGI server.
Sets a timeout for scgi cache lock. When the time expires, the request will
be passed to the SCGI server, however, the response will not be cached.
Before 1.7.8, the response could be cached.
Sets an offset in bytes for byte-range requests. If the range is beyond the
offset, the range request will be passed to the SCGI server and the response
will not be cached.
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 scgi no cache directive.
Sets the number of requests after which the response will be cached.
Sets the path and other parameters of a cache. Cache data are stored in
files. The file name in a cache is a result of applying the MD5 function to
the cache key. The levels parameter defines hierarchy levels of a cache:
from 1 to 3, each level accepts values 1 or 2. For example, in the following
configuration
/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 are put on the same file system. A directory for temporary files
is set based on the use_temp_path parameter (1.7.10). If this parameter is
omitted or set to the value on, the directory set by the scgi temp path directive
for the given location will be used. If the value is set to off, temporary files
will be put directly in the cache directory.
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. One megabyte zone can store about 8 thousand keys.
for the same number of keys. For example, one megabyte zone can store
about 4 thousand keys.
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. The data is removed in iterations
configured by manager_files, manager_threshold, and manager_-
sleep parameters (1.11.5). During one iteration no more than manager_-
files items are deleted (by default, 100). The duration of one iteration
is limited by the manager_threshold parameter (by default, 200
milliseconds). Between iterations, a pause configured by the manager_sleep
parameter (by default, 50 milliseconds) is made.
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 also 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.
Additionally, the following parameters are available as part of our
commercial subscription:
purger=on|off
Instructs whether cache entries that match a wildcard key will be
removed from the disk by the cache purger (1.7.12). Setting the
parameter to on (default is off) will activate the “cache purger” process
that permanently iterates through all cache entries and deletes the entries
that match the wildcard key.
purger_files=number
Sets the number of items that will be scanned during one iteration
(1.7.12). By default, purger_files is set to 10.
purger_threshold=number
Sets the duration of one iteration (1.7.12). By default, purger_-
threshold is set to 50 milliseconds.
purger_sleep=number
Sets a pause between iterations (1.7.12). By default, purger_sleep is
set to 50 milliseconds.
In versions 1.7.3, 1.7.7, and 1.11.10 cache header format has been changed.
Previously cached responses will be considered invalid after upgrading to a
newer nginx version.
Defines conditions under which the request will be considered a cache purge
request. If at least one value of the string parameters is not empty and
is not equal to “0” then the cache entry with a corresponding cache key is
removed. The result of successful operation is indicated by returning the 204
No Content response.
If the cache key of a purge request ends with an asterisk (“*”), all cache
entries matching the wildcard key will be removed from the cache. However,
these entries will remain on the disk until they are deleted for either inactivity,
or processed by the cache purger (1.7.12), or a client attempts to access them.
Example configuration:
server {
...
location / {
scgi_pass backend;
scgi_cache cache_zone;
scgi_cache_key $uri;
scgi_cache_purge $purge_method;
}
}
Sets caching time for different response codes. For example, the following
directives
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
scgi_cache_valid 5m;
Parameters of caching can also be set directly in the response header. This
has higher priority than setting of caching time using the directive.
• If the header includes the Set-Cookie field, such a response will not
be cached.
• If the header includes the Vary field with the special value “*”, such a
response will not be cached (1.7.7). If the header includes the Vary field
with another value, such a response will be cached taking into account
the corresponding request header fields (1.7.7).
Processing of one or more of these response header fields can be disabled using
the scgi ignore headers directive.
Enables byte-range support for both cached and uncached responses from
the SCGI server regardless of the Accept-Ranges field in these responses.
By default, nginx does not pass the header fields Status and
X-Accel-... from the response of an SCGI server to a client. The scgi_-
hide_header directive sets additional fields that will not be passed. If, on
the contrary, the passing of fields needs to be permitted, the scgi pass header
directive can be used.
Limits the speed of reading the response from the SCGI server. The rate is
specified in bytes per second. The zero value disables rate limiting. The limit
is set per a request, and so if nginx simultaneously opens two connections to
the SCGI server, the overall rate will be twice as much as the specified limit.
The limitation works only if buffering of responses from the SCGI server is
enabled.
When buffering of responses from the SCGI server is enabled, and the
whole response does not fit into the buffers set by the scgi buffer size and
scgi buffers directives, a part of the response can be saved to a temporary file.
This directive sets the maximum size of the temporary file. The size of data
written to the temporary file at a time is set by the scgi temp file write size
directive.
The zero value disables buffering of responses to temporary files.
This restriction does not apply to responses that will be cached or stored
on disk.
error
an error occurred while establishing a connection with the server, passing
a request to it, or reading the response header;
timeout
a timeout has occurred while establishing a connection with the server,
passing a request to it, or reading the response header;
invalid_header
a server returned an empty or invalid response;
http_500
a server returned a response with the code 500;
http_503
a server returned a response with the code 503;
http_403
a server returned a response with the code 403;
http_404
a server returned a response with the code 404;
http_429
a server returned a response with the code 429 (1.11.13);
non_idempotent
normally, requests with a non-idempotent method (POST, LOCK, PATCH)
are not passed to the next server if a request has been sent to an
upstream server (1.9.13); enabling this option explicitly allows retrying
such requests;
off
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_503, and http_-
429 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.
Passing a request to the next server can be limited by the number of tries
and by time.
Limits the time during which a request can be passed to the next server.
The 0 value turns off this limitation.
Limits the number of possible tries for passing a request to the next server.
The 0 value turns off this limitation.
scgi no cache
Syntax: scgi_no_cache 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:
scgi param
Syntax: scgi_param parameter value [if_not_empty];
Default —
Context: http, server, location
Sets a parameter that should be passed to the SCGI server. The value can
contain text, variables, and their combination. These directives are inherited
from the previous level if and only if there are no scgi_param directives
defined on the current level.
Standard CGI environment variables should be provided as SCGI headers,
see the scgi_params file provided in the distribution:
location / {
include scgi_params;
...
}
scgi pass
Syntax: scgi_pass address;
Default —
Context: location, if in location
scgi_pass localhost:9000;
scgi_pass unix:/tmp/scgi.socket;
Indicates whether the original request body is passed to the SCGI server.
See also the scgi pass request headers directive.
Indicates whether the header fields of the original request are passed to the
SCGI server. See also the scgi pass request body directive.
Defines a timeout for reading a response from the SCGI server. The timeout
is set only between two successive read operations, not for the transmission of
the whole response. If the SCGI server does not transmit anything within this
time, the connection is closed.
Sets a timeout for transmitting a request to the SCGI server. The timeout
is set only between two successive write operations, not for the transmission
of the whole request. If the SCGI server does not receive anything within this
time, the connection is closed.
scgi store
Syntax: scgi_store on | off | 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:
scgi_store /data/www$original_uri;
This directive can be used to create local copies of static unchangeable files,
e.g.:
location /images/ {
root /data/www;
error_page 404 = /fetch$uri;
}
location /fetch/ {
internal;
scgi_pass backend:9000;
...
scgi_store on;
scgi_store_access user:rw group:rw all:r;
scgi_temp_path /data/temp;
alias /data/www/;
}
Sets access permissions for newly created files and directories, e.g.:
Limits the size of data written to a temporary file at a time, when buffering
of responses from the SCGI server to temporary files is enabled. By default, size
is limited by two buffers set by the scgi buffer size and scgi buffers directives.
The maximum size of a temporary file is set by the scgi max temp file size
directive.
Defines a directory for storing temporary files with data received from SCGI
servers. Up to three-level subdirectory hierarchy can be used underneath the
specified directory. For example, in the following configuration
scgi_temp_path /spool/nginx/scgi_temp 1 2;
/spool/nginx/scgi_temp/7/45/00000123457
See also the use_temp_path parameter of the scgi cache path directive.
2.42.1 Summary
The ngx_http_secure_link_module module (0.7.18) is used to check
authenticity of requested links, protect resources from unauthorized access, and
limit link lifetime.
The authenticity of a requested link is verified by comparing the checksum
value passed in a request with the value computed for the request. If a link has
a limited lifetime and the time has expired, the link is considered outdated.
The status of these checks is made available in the $secure link variable.
The module provides two alternative operation modes. The first mode is
enabled by the secure link secret directive and is used to check authenticity
of requested links as well as protect resources from unauthorized access.
The second mode (0.8.50) is enabled by the secure link and secure link md5
directives and is also used to limit lifetime of links.
This module is not built by default, it should be enabled with the
--with-http_secure_link_module configuration parameter.
2.42.2 Directives
secure link
Syntax: secure_link expression;
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
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.
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:
/prefix/hash/link
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:
2.43.1 Summary
The ngx_http_session_log_module module enables logging sessions
(that is, aggregates of multiple HTTP requests) instead of individual HTTP
requests.
location /media/ {
session_log one;
}
2.43.3 Directives
session log
Syntax: session_log name | off;
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.
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.
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.
$session log id
current session ID;
$session log binary id
current session ID in binary form (16 bytes).
2.44.1 Summary
The ngx_http_slice_module module (1.9.8) is a filter that splits a
request into subrequests, each returning a certain range of response. The filter
provides more effective caching of big responses.
This module is not built by default, it should be enabled with the
--with-http_slice_module configuration parameter.
location / {
slice 1m;
proxy_cache cache;
proxy_cache_key $uri$is_args$args$slice_range;
proxy_set_header Range $slice_range;
proxy_cache_valid 200 206 1h;
proxy_pass http://localhost:8000;
}
2.44.3 Directives
slice
Syntax: slice size;
Default 0
Context: http, server, location
Sets the size of the slice. The zero value disables splitting responses into
slices. Note that a too low value may result in excessive memory usage and
opening a large number of files.
In order for a subrequest to return the required range, the $slice range
variable should be passed to the proxied server as the Range request header
field. If caching is enabled, $slice range should be added to the cache key and
caching of responses with 206 status code should be enabled.
$slice range
the current slice range in HTTP byte range format, for example,
bytes=0-1048575.
2.45.1 Summary
The ngx_http_split_clients_module module creates variables
suitable for A/B testing, also known as split testing.
http {
split_clients "${remote_addr}AAA" $variant {
0.5% .one;
2.0% .two;
* "";
}
server {
location / {
index index${variant}.html;
2.45.3 Directives
split clients
Syntax: split_clients string $variable { . . . }
Default —
Context: http
2.46.1 Summary
The ngx_http_ssi_module module is a filter that processes SSI (Server
Side Includes) commands in responses passing through it. Currently, the list
of supported SSI commands is incomplete.
location / {
ssi on;
...
}
2.46.3 Directives
ssi
Syntax: ssi on | off;
Default off
Context: http, server, location, if in location
Sets the minimum size for parts of a response stored on disk, starting from
which it makes sense to send them using sendfile.
ssi types
Syntax: ssi_types mime-type . . . ;
Default text/html
Context: http, server, location
Example:
config
Sets some parameters used during SSI processing, namely:
errmsg
a string that is output if an error occurs during SSI processing. By
default, the following string is output:
timefmt
a format string passed to the strftime function used to output
date and time. By default, the following format is used:
if
Performs a conditional inclusion. The following commands are
supported:
Only one level of nesting is currently supported. The command has the
following parameter:
expr
expression. An expression can be:
• variable existence check:
include
Includes the result of another request into a response. The command has
the following parameters:
file
specifies an included file, for example:
virtual
specifies an included request, for example:
stub
a non-standard parameter that names the block whose content will
be output if the included request results in an empty body or if an
error occurs during the request processing, for example:
set
a non-standard parameter that instructs to write a successful result
of request processing to the specified variable, for example:
location /remote/ {
subrequest_output_buffer_size 64k;
...
}
$date local
current time in the local time zone. The format is set by the config
command with the timefmt parameter.
$date gmt
current time in GMT. The format is set by the config command with
the timefmt parameter.
2.47.1 Summary
The ngx_http_ssl_module module provides the necessary support for
HTTPS.
This module is not built by default, it should be enabled with the
--with-http_ssl_module configuration parameter.
worker_processes auto;
http {
...
server {
listen 443 ssl;
keepalive_timeout 70;
...
}
2.47.3 Directives
ssl
Syntax: ssl on | off;
Default off
Context: http, server
This directive was made obsolete in version 1.15.0. The ssl parameter of
the listen directive should be used instead.
ssl_buffer_size 4k;
ssl certificate
Syntax: ssl_certificate 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.
Since version 1.11.0, this directive can be specified multiple times to load
certificates of different types, for example, RSA and ECDSA:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate example.com.rsa.crt;
ssl_certificate_key example.com.rsa.key;
ssl_certificate example.com.ecdsa.crt;
ssl_certificate_key example.com.ecdsa.key;
...
}
Specifies a file with the secret key in the PEM format for the given virtual
server.
The value engine:name:id can be specified instead of the file (1.7.9), which
loads a secret key with a specified id from the OpenSSL engine name.
ssl ciphers
Syntax: ssl_ciphers 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.
ssl crl
Syntax: ssl_crl file;
Default —
Context: http, server
This directive appeared in version 0.8.7.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify client certificates.
ssl dhparam
Syntax: ssl_dhparam file;
Default —
Context: http, server
This directive appeared in version 0.7.2.
ssl_ecdh_curve prime256v1:secp384r1;
The special value auto (1.11.0) instructs nginx to use a list built into the
OpenSSL library when using OpenSSL 1.0.2 or higher, or prime256v1 with
older versions.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Example:
http {
ssl_password_file /etc/keys/global.pass;
...
server {
server_name www1.example.com;
ssl_certificate_key /etc/keys/first.key;
}
server {
server_name www2.example.com;
Specifies that server ciphers should be preferred over client ciphers when
using the SSLv3 and TLS protocols.
ssl protocols
Syntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]
[TLSv1.3];
Default TLSv1 TLSv1.1 TLSv1.2
Context: http, server
The TLSv1.1 and TLSv1.2 parameters (1.1.13, 1.0.12) work only when
OpenSSL 1.0.1 or higher is used.
The TLSv1.3 parameter (1.13.0) works only when OpenSSL 1.1.1 built
with TLSv1.3 support is used.
Sets the types and sizes of caches that store session parameters. A cache
can be of any of the following types:
off
the use of a session cache is strictly prohibited: nginx explicitly tells a
client that sessions may not be reused.
none
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.
builtin
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.
shared
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:
but using only shared cache without the built-in cache should be more
efficient.
Sets a file with the secret key used to encrypt and decrypt TLS session
tickets. The directive is necessary if the same key has to be shared between
multiple servers. By default, a randomly generated key is used.
If several keys are specified, only the first key is used to encrypt TLS session
tickets. This allows configuring key rotation, for example:
ssl_session_ticket_key current.key;
ssl_session_ticket_key previous.key;
The file must contain 80 or 48 bytes of random data and can be created
using the following command:
Depending on the file size either AES256 (for 80-byte keys, 1.11.8) or
AES128 (for 48-byte keys) is used for encryption.
Specifies a time during which a client may reuse the session parameters.
ssl stapling
Syntax: ssl_stapling on | off;
Default off
Context: http, server
This directive appeared in version 1.3.7.
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.
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.
ssl_stapling_responder http://ocsp.example.com/;
495
an error has occurred during the client certificate verification;
496
a client has not presented the required certificate;
497
a regular request has been sent to the HTTPS port.
The redirection happens after the request is fully parsed and the variables,
such as $request uri, $uri, $args and others, are available.
$ssl cipher
returns the string of ciphers used for an established SSL connection;
$ssl ciphers
returns the list of ciphers supported by the client (1.11.7). Known ciphers
are listed by names, unknown are shown in hexadecimal, for example:
AES128-SHA:AES256-SHA:0x00ff
The variable is fully supported only when using OpenSSL version 1.0.2
or higher. With older versions, the variable is available only for new
sessions and lists only known ciphers.
The variable is deprecated, the $ssl client escaped cert variable should
be used instead.
Prior to version 1.11.6, the variable name was $ssl client i dn.
Prior to version 1.11.6, the variable name was $ssl client s dn.
Prior to version 1.11.7, the “FAILED” result did not contain the reason
string.
$ssl curves
returns the list of curves supported by the client (1.11.7). Known curves
are listed by names, unknown are shown in hexadecimal, for example:
0x001d:prime256v1:secp521r1:secp384r1
$ssl protocol
returns the protocol of an established SSL connection;
$ssl server name
returns the server name requested through SNI (1.7.0);
$ssl session id
returns the session identifier of an established SSL connection;
$ssl session reused
returns “r” if an SSL session was reused, or “.” otherwise (1.5.11).
2.48.1 Summary
The ngx_http_status_module module provides access to various
status information.
http {
upstream backend {
zone http_backend 64k;
server {
server_name backend.example.com;
location / {
proxy_pass http://backend;
proxy_cache cache_backend;
health_check;
}
status_zone server_backend;
}
server {
listen 127.0.0.1;
location /upstream_conf {
upstream_conf;
}
location /status {
status;
}
location = /status.html {
}
}
}
stream {
upstream backend {
zone stream_backend 64k;
server {
listen 127.0.0.1:12345;
proxy_pass backend;
status_zone server_backend;
health_check;
}
}
http://127.0.0.1/status
http://127.0.0.1/status/nginx_version
http://127.0.0.1/status/caches/cache_backend
http://127.0.0.1/status/upstreams
http://127.0.0.1/status/upstreams/backend
http://127.0.0.1/status/upstreams/backend/peers/1
http://127.0.0.1/status/upstreams/backend/peers/1/weight
http://127.0.0.1/status/stream
http://127.0.0.1/status/stream/upstreams
http://127.0.0.1/status/stream/upstreams/backend
http://127.0.0.1/status/stream/upstreams/backend/peers/1
http://127.0.0.1/status/stream/upstreams/backend/peers/1/weight
2.48.3 Directives
status
Syntax: status;
Default —
Context: location
status format
Syntax: status_format json;
Syntax: status_format jsonp [callback];
Default json
Context: http, server, location
status zone
Syntax: status_zone zone;
Default —
Context: server
2.48.4 Data
The following status information is provided:
version
Version of the provided data set. The current version is 8.
nginx_version
Version of nginx.
nginx_build
Name of nginx build.
address
The address of the server that accepted status request.
generation
The total number of configuration reloads.
load_timestamp
Time of the last reload of configuration, in milliseconds since Epoch.
timestamp
Current time in milliseconds since Epoch.
pid
The ID of the worker process that handled status request.
ppid
The ID of the master process that started the worker process.
processes
respawned
The total number of abnormally terminated and respawned child
processes.
connections
accepted
The total number of accepted client connections.
dropped
The total number of dropped client connections.
active
The current number of active client connections.
idle
The current number of idle client connections.
ssl
handshakes
The total number of successful SSL handshakes.
handshakes_failed
The total number of failed SSL handshakes.
session_reuses
The total number of session reuses during SSL handshake.
requests
total
The total number of client requests.
current
The current number of client requests.
server_zones
For each status zone:
processing
The number of client requests that are currently being processed.
requests
The total number of client requests received from clients.
responses
total
The total number of responses sent to clients.
1xx, 2xx, 3xx, 4xx, 5xx
The number of responses with status codes 1xx, 2xx, 3xx, 4xx,
and 5xx.
discarded
The total number of requests completed without sending a response.
received
The total number of bytes received from clients.
sent
The total number of bytes sent to clients.
slabs
For each shared memory zone that uses slab allocator:
pages
used
The current number of used memory pages.
free
The current number of free memory pages.
slots
For each memory slot size (8, 16, 32, 64, 128, etc.) the following
data are provided:
used
The current number of used memory slots.
free
The current number of free memory slots.
reqs
The total number of attempts to allocate memory of specified
size.
fails
The number of unsuccessful attempts to allocate memory of
specified size.
upstreams
For each dynamically configurable group, the following data are provided:
peers
For each server, the following data are provided:
id
The ID of the server.
server
An address of the server.
name
The name of the server specified in the server directive.
service
The service parameter value of the server directive.
backup
A boolean value indicating whether the server is a backup
server.
weight
Weight of the server.
state
Current state, which may be one of “up”, “draining”, “down”,
“unavail”, “checking”, or “unhealthy”.
active
The current number of active connections.
max_conns
The max conns limit for the server.
requests
The total number of client requests forwarded to this server.
responses
total
The total number of responses obtained from this server.
1xx, 2xx, 3xx, 4xx, 5xx
The number of responses with status codes 1xx, 2xx, 3xx,
4xx, and 5xx.
sent
The total number of bytes sent to this server.
received
The total number of bytes received from this server.
fails
The total number of unsuccessful attempts to communicate
with the server.
unavail
How many times the server became unavailable for client
requests (state “unavail”) due to the number of unsuccessful
attempts reaching the max fails threshold.
health_checks
checks
The total number of health check requests made.
fails
The number of failed health checks.
unhealthy
How many times the server became unhealthy (state
“unhealthy”).
last_passed
Boolean indicating if the last health check request was
successful and passed tests.
downtime
Total time the server was in the “unavail”, “checking”, and
“unhealthy” states.
downstart
The time (in milliseconds since Epoch) when the server became
“unavail”, “checking”, or “unhealthy”.
selected
The time (in milliseconds since Epoch) when the server was last
selected to process a request (1.7.5).
header_time
The average time to get the response header from the server
(1.7.10). Prior to version 1.11.6, the field was available only
when using the least time load balancing method.
response_time
The average time to get the full response from the server
(1.7.10). Prior to version 1.11.6, the field was available only
when using the least time load balancing method.
keepalive
The current number of idle keepalive connections.
zombies
The current number of servers removed from the group but still
processing active client requests.
zone
The name of the shared memory zone that keeps the group’s
configuration and run-time state.
queue
For the requests queue, the following data are provided:
size
The current number of requests in the queue.
max_size
The maximum number of requests that can be in the queue at
the same time.
overflows
The total number of requests rejected due to the queue overflow.
caches
For each cache (configured by proxy cache path and the likes):
size
The current size of the cache.
max_size
The limit on the maximum size of the cache specified in the
configuration.
cold
A boolean value indicating whether the “cache loader” process is
still loading data from disk into the cache.
hit, stale, updating, revalidated
responses
The total number of responses read from the cache (hits, or
stale responses due to proxy cache use stale and the likes).
bytes
The total number of bytes read from the cache.
miss, expired, bypass
responses
The total number of responses not taken from the cache (misses,
expires, or bypasses due to proxy cache bypass and the likes).
bytes
The total number of bytes read from the proxied server.
responses_written
The total number of responses written to the cache.
bytes_written
The total number of bytes written to the cache.
stream
server_zones
For each status zone:
processing
The number of client connections that are currently being
processed.
connections
The total number of connections accepted from clients.
sessions
total
The total number of completed client sessions.
2xx, 4xx, 5xx
The number of sessions completed with status codes 2xx,
4xx, or 5xx.
discarded
The total number of connections completed without creating a
session.
received
The total number of bytes received from clients.
sent
The total number of bytes sent to clients.
upstreams
For each dynamically configurable group, the following data are
provided:
peers
For each server the following data are provided:
id
The ID of the server.
server
An address of the server.
name
The name of the server specified in the server directive.
service
The service parameter value of the server directive.
backup
A boolean value indicating whether the server is a backup
server.
weight
Weight of the server.
state
Current state, which may be one of “up”, “down”,
“unavail”, “checking”, or “unhealthy”.
active
The current number of connections.
max_conns
The max conns limit for the server.
connections
The total number of client connections forwarded to this
server.
connect_time
The average time to connect to the upstream server. Prior
to version 1.11.6, the field was available only when using
the least time load balancing method.
first_byte_time
The average time to receive the first byte of data. Prior to
version 1.11.6, the field was available only when using the
least time load balancing method.
response_time
The average time to receive the last byte of data. Prior to
version 1.11.6, the field was available only when using the
least time load balancing method.
sent
The total number of bytes sent to this server.
received
The total number of bytes received from this server.
fails
The total number of unsuccessful attempts to communicate
with the server.
unavail
How many times the server became unavailable for client
connections (state “unavail”) due to the number of
unsuccessful attempts reaching the max fails threshold.
health_checks
checks
The total number of health check requests made.
fails
The number of failed health checks.
unhealthy
How many times the server became unhealthy (state
“unhealthy”).
last_passed
Boolean indicating if the last health check request was
successful and passed tests.
downtime
Total time the server was in the “unavail”, “checking”,
and “unhealthy” states.
downstart
The time (in milliseconds since Epoch) when the server
became “unavail”, “checking”, or “unhealthy”.
selected
The time (in milliseconds since Epoch) when the server was
last selected to process a connection.
zombies
The current number of servers removed from the group but still
processing active client connections.
zone
The name of the shared memory zone that keeps the group’s
configuration and run-time state.
2.48.5 Compatibility
• The zone field in http and stream upstreams was added in version 8.
• The name and service fields in http and stream upstreams were added in
version 8.
• The sessions status data and the discarded field in stream server zones
were added in version 7.
• The zombies field was moved from nginx debug version in version 6.
• The header time and response time fields in upstreams were added in
version 5.
• The server zones, caches, and load timestamp status data were added in
version 2.
2.49.1 Summary
The ngx_http_stub_status_module module provides access to basic
status information.
This module is not built by default, it should be enabled with the
--with-http_stub_status_module configuration parameter.
location = /basic_status {
stub_status;
}
This configuration creates a simple web page with basic status data which
may look like as follows:
2.49.3 Directives
stub status
Syntax: stub_status;
Default —
Context: server, location
2.49.4 Data
The following status information is provided:
Active connections
The current number of active client connections including Waiting
connections.
accepts
The total number of accepted client connections.
handled
The total number of handled connections. Generally, the parameter value
is the same as accepts unless some resource limits have been reached
(for example, the worker connections limit).
requests
The total number of client requests.
Reading
The current number of connections where nginx is reading the request
header.
Writing
The current number of connections where nginx is writing the response
back to the client.
Waiting
The current number of idle client connections waiting for a request.
$connections active
same as the Active connections value;
$connections reading
same as the Reading value;
$connections writing
same as the Writing value;
$connections waiting
same as the Waiting value.
2.50.1 Summary
The ngx_http_sub_module module is a filter that modifies a response
by replacing one specified string by another.
This module is not built by default, it should be enabled with the
--with-http_sub_module configuration parameter.
location / {
sub_filter ’<a href="http://127.0.0.1:8080/’ ’<a href="https://$host/’;
sub_filter ’<img src="http://127.0.0.1:8080/’ ’<img src="https://$host/’;
sub_filter_once on;
}
2.50.3 Directives
sub filter
Syntax: sub_filter string replacement;
Default —
Context: http, server, location
2.51.1 Summary
The ngx_http_upstream_module module is used to define groups of
servers that can be referenced by the proxy pass, fastcgi pass, uwsgi pass,
scgi pass, memcached pass, and grpc pass directives.
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server {
location / {
proxy_pass http://backend;
}
}
resolver 10.0.0.1;
upstream dynamic {
zone upstream_dynamic 64k;
server {
location / {
proxy_pass http://dynamic;
health_check;
}
}
2.51.3 Directives
upstream
Syntax: upstream name { . . . }
Default —
Context: http
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
Syntax: 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:
weight=number
sets the weight of the server, by default, 1.
max_conns=number
limits the maximum number of simultaneous active connections to the
proxied server (1.11.5). Default value is zero, meaning there is no limit.
If the server group does not reside in the shared memory, the limitation
works per each worker process.
Since version 1.5.9 and prior to version 1.11.5, this parameter was
available as part of our commercial subscription.
max_fails=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, uwsgi -
next upstream, scgi next upstream, memcached next upstream, and
grpc next upstream directives.
fail_timeout=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.
backup
marks the server as a backup server. It will be passed requests when the
primary servers are unavailable.
down
marks the server as permanently unavailable.
http {
resolver 10.0.0.1;
upstream u {
zone ...;
...
server example.com resolve;
}
}
route=string
sets the server route name.
service=name
enables resolving of DNS SRV records and sets the service name (1.9.13).
In order for this parameter to work, it is necessary to specify the resolve
parameter for the server and specify a hostname without a port number.
If the service name does not contain a dot (“.”), then the RFC-compliant
name is constructed and the TCP protocol is added to the service prefix.
For example, to look up the _http._tcp.backend.example.com
SRV record, it is necessary to specify the directive:
If the service name contains one or more dots, then the name is
constructed by joining the service prefix and the server name. For
example, to look up the _http._tcp.backend.example.com and
server1.backend.example.com SRV records, it is necessary to
specify the directives:
The parameter cannot be used along with the hash and ip hash load
balancing methods.
drain
puts the server into the “draining” mode (1.13.6). In this mode, only
requests bound to the server will be proxied to it.
Prior to version 1.13.6, the parameter could be changed only with the
API module.
zone
Syntax: zone name [size];
Default —
Context: upstream
This directive appeared in version 1.9.0.
Defines the name and size of the shared memory zone that keeps the group’s
configuration and run-time state that are shared between worker processes.
Several groups may share the same zone. In this case, it is enough to specify
the size only once.
Additionally, as part of our commercial subscription, such groups allow
changing the group membership or modifying the settings of a particular server
without the need of restarting nginx. The configuration is accessible via the
API module (1.13.3).
Prior to version 1.13.3, the configuration was accessible only via a special
location handled by upstream conf.
state
Syntax: state file;
Default —
Context: upstream
This directive appeared in version 1.9.7.
Specifies a file that keeps the state of the dynamically configurable group.
Examples:
The state is currently limited to the list of servers with their parameters.
The file is read when parsing the configuration and is updated each time the
upstream configuration is changed. Changing the file content directly should
be avoided. The directive cannot be used along with the server directive.
hash
Syntax: hash key [consistent];
Default —
Context: upstream
This directive appeared in version 1.7.2.
Specifies a load balancing method for a server group where the client-server
mapping is based on the hashed key value. The key can contain text, variables,
and their combinations. Note that adding or removing a server from the group
may result in remapping most of the keys to different servers. The method is
compatible with the Cache::Memcached Perl library.
If the consistent parameter is specified the ketama consistent hashing
method will be used instead. The method ensures that only a few keys will be
remapped to different servers when a server is added to or removed from the
group. This helps to achieve a higher cache hit ratio for caching servers. The
method is compatible with the Cache::Memcached::Fast Perl library with the
ketama points parameter set to 160.
ip hash
Syntax: ip_hash;
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.
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.
keepalive
Syntax: keepalive connections;
Default —
Context: upstream
This directive appeared in version 1.1.4.
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 "";
...
}
}
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.
keepalive requests
Syntax: keepalive_requests number;
Default 100
Context: upstream
This directive appeared in version 1.15.3.
Sets the maximum number of requests that can be served through one
keepalive connection. After the maximum number of requests is made, the
connection is closed.
keepalive timeout
Syntax: keepalive_timeout timeout;
Default 60s
Context: upstream
This directive appeared in version 1.15.3.
ntlm
Syntax: ntlm;
Default —
Context: upstream
This directive appeared in version 1.9.2.
upstream http_backend {
server 127.0.0.1:8080;
ntlm;
}
server {
...
location /http/ {
proxy_pass http://http_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
...
}
}
When using load balancer methods other than the default round-robin
method, it is necessary to activate them before the ntlm directive.
least conn
Syntax: least_conn;
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 in
turn using a weighted round-robin balancing method.
least time
Syntax: least_time header | last_byte [inflight];
Default —
Context: upstream
This directive appeared in version 1.7.10.
Specifies that a group should use a load balancing method where a request
is passed to the server with the least average response time and least number of
active connections, taking into account weights of servers. If there are several
such servers, they are tried in turn using a weighted round-robin balancing
method.
If the header parameter is specified, time to receive the response header
is used. If the last_byte parameter is specified, time to receive the full
response is used. If the inflight parameter is specified (1.11.6), incomplete
requests are also taken into account.
queue
Syntax: queue number [timeout=time];
Default —
Context: upstream
This directive appeared in version 1.5.12.
When using load balancer methods other than the default round-robin
method, it is necessary to activate them before the queue directive.
random
Syntax: random [two [method]];
Default —
Context: upstream
This directive appeared in version 1.15.1.
Specifies that a group should use a load balancing method where a request
is passed to a randomly selected server, taking into account weights of servers.
The optional two parameter instructs nginx to randomly select two servers
and then choose a server using the specified method. The default method is
least_conn which passes a request to a server with the least number of
active connections.
The least_time method passes a request to a server with the least
average response time and least number of active connections. If least_-
time=header is specified, the time to receive the response header is used. If
least_time=last_byte is specified, the time to receive the full response
is used.
sticky
Syntax: sticky cookie name [expires=time] [domain=domain] [httponly]
[secure] [path=path];
Syntax: sticky route $variable . . . ;
Syntax: sticky learn create=$variable lookup=$variable zone=name:size
[timeout=time] [header] [sync];
Default —
Context: upstream
This directive appeared in version 1.5.7.
Enables session affinity, which causes requests from the same client to be
passed to the same server in a group of servers. Three methods are available:
cookie
When the cookie method is used, information about the designated
server is passed in an HTTP cookie generated by nginx:
upstream backend {
server backend1.example.com;
server backend2.example.com;
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 with this cookie will be passed to the designated 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.
The cookie value is a hexadecimal representation of the MD5 hash of
the IP address and port, or of the UNIX-domain socket path. However,
if the “route” parameter of the server directive is specified, the cookie
value will be the value of the “route” parameter:
upstream backend {
server backend1.example.com route=a;
server backend2.example.com route=b;
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:
upstream backend {
server backend1.example.com route=a;
server backend2.example.com route=b;
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8081;
sticky learn
create=$upstream_cookie_examplecookie
lookup=$cookie_examplecookie
zone=client_sessions:1m;
}
memory zone.
2.52.1 Summary
The ngx_http_upstream_conf_module module allows configuring
upstream server groups on-the-fly via a simple HTTP interface without the
need of restarting nginx. The http or stream server group must reside in the
shared memory.
upstream backend {
zone upstream_backend 64k;
...
}
server {
location /upstream_conf {
upstream_conf;
allow 127.0.0.1;
deny all;
}
}
2.52.3 Directives
upstream conf
Syntax: upstream_conf;
Default —
Context: location
http://127.0.0.1/upstream_conf?upstream=backend
server=address
Same as the “address” parameter of the http or stream upstream server.
When adding a server, it is possible to specify it as a domain name.
In this case, changes of the IP addresses that correspond to a domain
name will be monitored and automatically applied to the upstream
configuration without the need of restarting nginx (1.7.2). This requires
the “resolver” directive in the http or stream block. See also the
“resolve” parameter of the http or stream upstream server.
service=name
Same as the “service” parameter of the http or stream upstream server
(1.9.13).
weight=number
Same as the “weight” parameter of the http or stream upstream server.
max_conns=number
Same as the “max_conns” parameter of the http or stream upstream
server.
max_fails=number
Same as the “max_fails” parameter of the http or stream upstream
server.
fail_timeout=time
Same as the “fail_timeout” parameter of the http or stream upstream
server.
slow_start=time
Same as the “slow_start” parameter of the http or stream upstream
server.
down=
Same as the “down” parameter of the http or stream upstream server.
drain=
Puts the http upstream server into the “draining” mode (1.7.5). In this
mode, only requests bound to the server will be proxied to it.
up=
The opposite of the “down” parameter of the http or stream upstream
server.
route=string
Same as the “route” parameter of the http upstream server.
The first three parameters select an object. This can be either the whole
http or stream upstream server group, or a specific server. Without other
parameters, the configuration of the selected group or server is shown.
For example, to view the configuration of the whole group, send:
http://127.0.0.1/upstream_conf?upstream=backend
http://127.0.0.1/upstream_conf?upstream=backend&id=42
http://127.0.0.1/upstream_conf?add=&upstream=backend&server=127.0.0.1:8080
http://127.0.0.1/upstream_conf?add=&upstream=backend&backup=&server
=127.0.0.1:8080
To add a new primary server, set its parameters to non-default values and
mark it as “down”, send:
http://127.0.0.1/upstream_conf?add=&upstream=backend&server=127.0.0.1:8080&
weight=2&down=
http://127.0.0.1/upstream_conf?remove=&upstream=backend&id=42
http://127.0.0.1/upstream_conf?upstream=backend&id=42&down=
http://127.0.0.1/upstream_conf?upstream=backend&id=42&server=192.0.2.3:8123
http://127.0.0.1/upstream_conf?upstream=backend&id=42&max_fails=3&weight=4
The above examples are for an http upstream server group. Similar
examples for a stream upstream server group require the “stream=”
parameter.
2.53.1 Summary
The ngx_http_upstream_hc_module module allows enabling periodic
health checks of the servers in a group referenced in the surrounding location.
The server group must reside in the shared memory.
If a health check fails, the server will be considered unhealthy. 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. Client
requests are not passed to unhealthy servers and servers in the “checking” state.
Please note that most of the variables will have empty values when used
with health checks.
upstream dynamic {
zone upstream_dynamic 64k;
server {
location / {
proxy_pass http://dynamic;
health_check;
}
}
With this configuration, nginx 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.
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 of the health check directive:
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 shows that in order for a health check to pass, the
response to a health check request should succeed, have status 200, and contain
“Welcome to nginx!” in the body.
2.53.3 Directives
health check
Syntax: health_check [parameters];
Default —
Context: location
interval=time
sets the interval between two consecutive health checks, by default, 5
seconds.
jitter=time
sets the time within which each health check will be randomly delayed,
by default, there is no delay.
fails=number
sets the number of consecutive failed health checks of a particular server
after which this server will be considered unhealthy, by default, 1.
passes=number
sets the number of consecutive passed health checks of a particular server
after which the server will be considered healthy, by default, 1.
uri=uri
defines the URI used in health check requests, by default, “/”.
mandatory
sets the initial “checking” state for a server until the first health check
is completed (1.11.7). Client requests are not passed to servers in the
“checking” state. If the parameter is not specified, the server will be
initially considered healthy.
match=name
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.
port=number
defines the port used when connecting to a server to perform a health
check (1.9.7). By default, equals the server port.
match
Syntax: match name { . . . }
Default —
Context: http
Defines the named test set used to verify responses to health check requests.
The following items can be tested in a response:
status 200;
status is 200
status ! 500;
status is not 500
status 200 204;
status is 200 or 204
status ! 301 302;
status is neither 301 nor 302
status 200-399;
status is in the range from 200 to 399
status ! 400-599;
status is not in the range from 400 to 599
status 301-303 307;
status is either 301, 302, 303, or 307
If several tests are specified, the response matches only if it matches all
tests.
Examples:
# 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;
}
2.54.1 Summary
The ngx_http_userid_module module sets cookies suitable for client
identification. Received and set cookies can be logged using the embedded
variables $uid got and $uid set. This module is compatible with the mod uid
module for Apache.
userid on;
userid_name uid;
userid_domain example.com;
userid_path /;
userid_expires 365d;
userid_p3p ’policyref="/w3c/p3p.xml", CP="CUR ADM OUR NOR STA NID"’;
2.54.3 Directives
userid
Syntax: userid on | v1 | log | off;
Default off
Context: http, server, location
on
enables the setting of version 2 cookies and logging of the received
cookies;
v1
enables the setting of version 1 cookies and logging of the received
cookies;
log
disables the setting of cookies, but enables logging of the received cookies;
off
disables the setting of cookies and logging of the received cookies.
userid domain
Syntax: userid_domain name | none;
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.
userid expires
Syntax: userid_expires time | max | off;
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”.
The parameter off will cause the cookie to expire at the end of a browser
session.
userid mark
Syntax: userid_mark letter | digit | = | off;
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.
userid name
Syntax: userid_name name;
Default uid
Context: http, server, location
userid p3p
Syntax: userid_p3p string | none;
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.
userid path
Syntax: userid_path path;
Default /
Context: http, server, location
userid service
Syntax: userid_service number;
Default IP address of the server
Context: http, server, location
$uid got
The cookie name and received client identifier.
$uid reset
If the variable is set to a non-empty string that is not “0”, the client
identifiers are reset. The special value “log” additionally leads to the
output of messages about the reset identifiers to the error log.
$uid set
The cookie name and sent client identifier.
2.55.1 Summary
The ngx_http_uwsgi_module module allows passing requests to a
uwsgi server.
location / {
include uwsgi_params;
uwsgi_pass localhost:9000;
}
2.55.3 Directives
uwsgi bind
Syntax: uwsgi_bind address [transparent] | off;
Default —
Context: http, server, location
Sets the size of the buffer used for reading the first part of the response
received from the uwsgi server. This part usually contains a small response
header. By default, the buffer size is equal to one memory page. This is either
4K or 8K, depending on a platform. It can be made smaller, however.
uwsgi buffering
Syntax: uwsgi_buffering on | off;
Default on
Context: http, server, location
uwsgi buffers
Syntax: uwsgi_buffers number size;
Default 8 4k|8k
Context: http, server, location
Sets the number and size of the buffers used for reading a response from
the uwsgi 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.
When buffering of responses from the uwsgi 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 meantime, the rest of the buffers can be
used for reading the response and, if needed, buffering part of the response to
a temporary file. By default, size is limited by the size of two buffers set by
the uwsgi buffer size and uwsgi buffers directives.
uwsgi cache
Syntax: uwsgi_cache zone | off;
Default off
Context: http, server, location
Defines a shared memory zone used for caching. The same zone can be
used in several places. Parameter value can contain variables (1.7.9). The off
parameter disables caching inherited from the previous configuration level.
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:
uwsgi_cache_key localhost:9000$request_uri;
When enabled, only one request at a time will be allowed to populate a new
cache element identified according to the uwsgi cache key directive by passing
a request to a uwsgi 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 uwsgi cache lock timeout
directive.
If the last request passed to the uwsgi server for populating a new cache
element has not completed for the specified time, one more request may be
passed to the uwsgi server.
Sets a timeout for uwsgi cache lock. When the time expires, the request
will be passed to the uwsgi server, however, the response will not be cached.
Sets an offset in bytes for byte-range requests. If the range is beyond the
offset, the range request will be passed to the uwsgi server and the response
will not be cached.
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 uwsgi no cache
directive.
Sets the number of requests after which the response will be cached.
Sets the path and other parameters of a cache. Cache data are stored in
files. The file name in a cache is a result of applying the MD5 function to
the cache key. The levels parameter defines hierarchy levels of a cache:
from 1 to 3, each level accepts values 1 or 2. For example, in the following
configuration
/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 are put on the same file system. A directory for
temporary files is set based on the use_temp_path parameter (1.7.10). If
this parameter is omitted or set to the value on, the directory set by the
uwsgi temp path directive for the given location will be used. If the value is
set to off, temporary files will be put directly in the cache directory.
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. One megabyte zone can store about 8 thousand keys.
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. The data is removed in iterations
configured by manager_files, manager_threshold, and manager_-
sleep parameters (1.11.5). During one iteration no more than manager_-
files items are deleted (by default, 100). The duration of one iteration
is limited by the manager_threshold parameter (by default, 200
milliseconds). Between iterations, a pause configured by the manager_sleep
parameter (by default, 50 milliseconds) is made.
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 also 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.
Additionally, the following parameters are available as part of our
commercial subscription:
purger=on|off
In versions 1.7.3, 1.7.7, and 1.11.10 cache header format has been changed.
Previously cached responses will be considered invalid after upgrading to a
newer nginx version.
Defines conditions under which the request will be considered a cache purge
request. If at least one value of the string parameters is not empty and
is not equal to “0” then the cache entry with a corresponding cache key is
removed. The result of successful operation is indicated by returning the 204
No Content response.
If the cache key of a purge request ends with an asterisk (“*”), all cache
entries matching the wildcard key will be removed from the cache. However,
these entries will remain on the disk until they are deleted for either inactivity,
or processed by the cache purger (1.7.12), or a client attempts to access them.
Example configuration:
server {
...
location / {
uwsgi_pass backend;
uwsgi_cache cache_zone;
uwsgi_cache_key $uri;
uwsgi_cache_purge $purge_method;
}
Sets caching time for different response codes. For example, the following
directives
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
uwsgi_cache_valid 5m;
Parameters of caching can also be set directly in the response header. This
has higher priority than setting of caching time using the directive.
• If the header includes the Set-Cookie field, such a response will not
be cached.
• If the header includes the Vary field with the special value “*”, such a
response will not be cached (1.7.7). If the header includes the Vary field
with another value, such a response will be cached taking into account
the corresponding request header fields (1.7.7).
Processing of one or more of these response header fields can be disabled using
the uwsgi ignore headers directive.
Enables byte-range support for both cached and uncached responses from
the uwsgi server regardless of the Accept-Ranges field in these responses.
By default, nginx does not pass the header fields Status and
X-Accel-... from the response of a uwsgi server to a client. The uwsgi_-
hide_header directive sets additional fields that will not be passed. If, on
the contrary, the passing of fields needs to be permitted, the uwsgi pass header
directive can be used.
Limits the speed of reading the response from the uwsgi server. The rate is
specified in bytes per second. The zero value disables rate limiting. The limit
is set per a request, and so if nginx simultaneously opens two connections to
the uwsgi server, the overall rate will be twice as much as the specified limit.
The limitation works only if buffering of responses from the uwsgi server is
enabled.
When buffering of responses from the uwsgi server is enabled, and the whole
response does not fit into the buffers set by the uwsgi buffer size and uwsgi -
buffers directives, a part of the response can be saved to a temporary file.
This directive sets the maximum size of the temporary file. The size of data
written to the temporary file at a time is set by the uwsgi temp file write size
directive.
The zero value disables buffering of responses to temporary files.
This restriction does not apply to responses that will be cached or stored
on disk.
uwsgi modifier1
Syntax: uwsgi_modifier1 number;
Default 0
Context: http, server, location
Sets the value of the modifier1 field in the uwsgi packet header.
uwsgi modifier2
Syntax: uwsgi_modifier2 number;
Default 0
Context: http, server, location
Sets the value of the modifier2 field in the uwsgi packet header.
Limits the time during which a request can be passed to the next server.
The 0 value turns off this limitation.
Limits the number of possible tries for passing a request to the next server.
The 0 value turns off this limitation.
uwsgi no cache
Syntax: uwsgi_no_cache 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:
uwsgi param
Syntax: uwsgi_param parameter value [if_not_empty];
Default —
Context: http, server, location
Sets a parameter that should be passed to the uwsgi server. The value can
contain text, variables, and their combination. These directives are inherited
from the previous level if and only if there are no uwsgi_param directives
defined on the current level.
Standard CGI environment variables should be provided as uwsgi headers,
see the uwsgi_params file provided in the distribution:
location / {
include uwsgi_params;
...
}
uwsgi pass
Syntax: uwsgi_pass [protocol://]address;
Default —
Context: location, if in location
uwsgi_pass localhost:9000;
uwsgi_pass uwsgi://localhost:9000;
uwsgi_pass suwsgi://[2001:db8::1]:9090;
uwsgi_pass unix:/tmp/uwsgi.socket;
Indicates whether the original request body is passed to the uwsgi server.
See also the uwsgi pass request headers directive.
Indicates whether the header fields of the original request are passed to the
uwsgi server. See also the uwsgi pass request body directive.
Defines a timeout for reading a response from the uwsgi server. The timeout
is set only between two successive read operations, not for the transmission of
the whole response. If the uwsgi server does not transmit anything within this
time, the connection is closed.
Sets a timeout for transmitting a request to the uwsgi server. The timeout
is set only between two successive write operations, not for the transmission
of the whole request. If the uwsgi server does not receive anything within this
time, the connection is closed.
Specifies a file with the certificate in the PEM format used for
authentication to a secured uwsgi server.
Specifies a file with the secret key in the PEM format used for
authentication to a secured uwsgi server.
The value engine:name:id can be specified instead of the file (1.7.9), which
loads a secret key with a specified id from the OpenSSL engine name.
Specifies the enabled ciphers for requests to a secured uwsgi server. The
ciphers are specified in the format understood by the OpenSSL library.
The full list can be viewed using the “openssl ciphers” command.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify the certificate of the secured uwsgi server.
Allows overriding the server name used to verify the certificate of the
secured uwsgi server and to be passed through SNI when establishing a
connection with the secured uwsgi server.
By default, the host part from uwsgi pass is used.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Enables or disables passing of the server name through TLS Server Name
Indication extension (SNI, RFC 6066) when establishing a connection with the
secured uwsgi server.
Sets the verification depth in the secured uwsgi server certificates chain.
uwsgi store
Syntax: uwsgi_store on | off | 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:
uwsgi_store /data/www$original_uri;
location /images/ {
root /data/www;
error_page 404 = /fetch$uri;
}
location /fetch/ {
internal;
uwsgi_pass backend:9000;
...
uwsgi_store on;
uwsgi_store_access user:rw group:rw all:r;
uwsgi_temp_path /data/temp;
alias /data/www/;
}
Sets access permissions for newly created files and directories, e.g.:
Limits the size of data written to a temporary file at a time, when buffering
of responses from the uwsgi server to temporary files is enabled. By default,
size is limited by two buffers set by the uwsgi buffer size and uwsgi buffers
directives. The maximum size of a temporary file is set by the uwsgi max -
temp file size directive.
Defines a directory for storing temporary files with data received from uwsgi
servers. Up to three-level subdirectory hierarchy can be used underneath the
specified directory. For example, in the following configuration
uwsgi_temp_path /spool/nginx/uwsgi_temp 1 2;
/spool/nginx/uwsgi_temp/7/45/00000123457
2.56.1 Summary
The ngx_http_v2_module module (1.9.5) provides support for HTTP/
2 and supersedes the ngx http spdy module module.
This module is not built by default, it should be enabled with the
--with-http_v2_module configuration parameter.
server {
listen 443 ssl http2;
ssl_certificate server.crt;
ssl_certificate_key server.key;
}
Also note that if the ssl prefer server ciphers directive is set to the value
“on”, the ciphers should be configured to comply with RFC 7540, Appendix A
black list and supported by clients.
2.56.4 Directives
http2 body preread size
Syntax: http2_body_preread_size size;
Default 64k
Context: http, server
This directive appeared in version 1.11.0.
Sets the size of the buffer per each request in which the request body may
be saved before it is started to be processed.
Sets the maximum size of chunks into which the response body is sliced. A
too low value results in higher overhead. A too high value impairs prioritization
due to HOL blocking.
Limits the maximum size of the entire request header list after HPACK
decompression. For most requests, the default limit should be enough.
Sets the maximum number of requests (including push requests) that can
be served through one HTTP/2 connection, after which the next client request
will lead to connection closing and the need of establishing a new connection.
http2 push
Syntax: http2_push uri | off;
Default off
Context: http, server, location
This directive appeared in version 1.13.9.
Pre-emptively sends (pushes) a request to the specified uri along with the
response to the original request. Only relative URIs with absolute path will
be processed, for example:
http2_push /static/css/main.css;
Sets the timeout for expecting more data from the client, after which the
connection is closed.
$http2
negotiated protocol identifier: “h2” for HTTP/2 over TLS, “h2c” for
HTTP/2 over cleartext TCP, or an empty string otherwise.
2.57.1 Summary
The ngx_http_xslt_module (0.7.8+) is a filter that transforms XML
responses using one or more XSLT stylesheets.
This module is not built by default, it should be enabled with the
--with-http_xslt_module configuration parameter.
location / {
xml_entities /site/dtd/entities.dtd;
xslt_stylesheet /site/xslt/one.xslt param=value;
xslt_stylesheet /site/xslt/two.xslt;
}
2.57.3 Directives
xml entities
Syntax: xml_entities 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:
xslt param
Syntax: xslt_param parameter value;
Default —
Context: http, server, location
This directive appeared in version 1.1.18.
xslt stylesheet
Syntax: xslt_stylesheet stylesheet [parameter=value . . . ];
Default —
Context: location
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;
}
xslt types
Syntax: xslt_types mime-type . . . ;
Default text/xml
Context: http, server, location
3.1.1 Summary
The ngx_stream_core_module module is available since version
1.9.0. This module is not built by default, it should be enabled with the
--with-stream configuration parameter.
worker_processes auto;
events {
worker_connections 1024;
}
stream {
upstream backend {
353
CHAPTER 3. STREAM SERVER MODULES 3.1. MODULE NGX STREAM CORE MODULE
upstream dns {
server 192.168.0.1:53535;
server dns.example.com:53;
}
server {
listen 12345;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass backend;
}
server {
listen 127.0.0.1:53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}
3.1.3 Directives
listen
Syntax: listen address:port [ssl] [udp] [proxy_protocol]
[backlog=number] [rcvbuf=size] [sndbuf=size] [bind]
[ipv6only=on|off] [reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default —
Context: server
Sets the address and port for the socket on which the server will accept
connections. It is possible to specify just the port. The address can also be a
hostname, for example:
listen 127.0.0.1:12345;
listen *:12345;
listen 12345; # same as *:12345
listen localhost:12345;
listen [::1]:12345;
listen [::]:12345;
listen unix:/var/run/nginx.sock;
The ssl parameter allows specifying that all connections accepted on this
port should work in SSL mode.
The udp parameter configures a listening socket for working with
datagrams (1.9.13).
The proxy_protocol parameter (1.11.4) allows specifying that all
connections accepted on this port should use the PROXY protocol.
backlog=number
sets the backlog parameter in the listen call that limits the
maximum length for the queue of pending connections (1.9.2). By
default, backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS,
and to 511 on other platforms.
rcvbuf=size
sets the receive buffer size (the SO_RCVBUF option) for the listening
socket (1.11.13).
sndbuf=size
sets the send buffer size (the SO_SNDBUF option) for the listening socket
(1.11.13).
bind
this parameter instructs to make a separate bind call for a given
address:port pair. The fact is that 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 getsockname system
call will be made in this case to determine the address that accepted the
connection. If the ipv6only or so_keepalive parameters are used
then for a given address:port pair a separate bind call will always be
made.
ipv6only=on|off
this parameter 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.
reuseport
this parameter (1.9.1) instructs to create an individual listening socket for
each worker process (using the SO_REUSEPORT socket option on Linux
3.9+ and DragonFly BSD, or SO_REUSEPORT_LB on FreeBSD 12+),
allowing a kernel to distribute incoming connections between worker
processes. This currently works only on Linux 3.9+, DragonFly BSD,
and FreeBSD 12+ (1.15.1).
so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]
this parameter 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.
Different servers must listen on different address:port pairs.
preread timeout
Syntax: preread_timeout timeout;
Default 30s
Context: stream, server
This directive appeared in version 1.11.5.
resolver
Syntax: resolver address . . . [valid=time] [ipv6=on|off];
Default —
Context: stream, server
This directive appeared in version 1.11.3.
resolver timeout
Syntax: resolver_timeout time;
Default 30s
Context: stream, server
This directive appeared in version 1.11.3.
resolver_timeout 5s;
server
Syntax: server { . . . }
Default —
Context: stream
stream
Syntax: stream { . . . }
Default —
Context: main
Provides the configuration file context in which the stream server directives
are specified.
tcp nodelay
Syntax: tcp_nodelay on | off;
Default on
Context: stream, server
This directive appeared in version 1.9.4.
Sets the bucket size for the variables hash table. The details of setting up
hash tables are provided in a separate document.
Sets the maximum size of the variables hash table. The details of setting
up hash tables are provided in a separate document.
$connection
connection serial number
$hostname
host name
$msec
current time in seconds with the milliseconds resolution
$nginx version
nginx version
$pid
PID of the worker process
$protocol
protocol used to communicate with the client: TCP or UDP (1.11.4)
$proxy protocol addr
client address from the PROXY protocol header, or an empty string
otherwise (1.11.4)
The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter in the listen directive.
$proxy protocol port
client port from the PROXY protocol header, or an empty string
otherwise (1.11.4)
The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter in the listen directive.
$remote addr
client address
$remote port
client port
$server addr
an address of the server which accepted a connection
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 port
port of the server which accepted a connection
$session time
session duration in seconds with a milliseconds resolution (1.11.4);
$status
session status (1.11.4), can be one of the following:
200
session completed successfully
400
client data could not be parsed, for example, the PROXY protocol
header
403
access forbidden, for example, when access is limited for certain
client addresses
500
internal server error
502
bad gateway, for example, if an upstream server could not be
selected or reached.
503
service unavailable, for example, when access is limited by the
number of connections
$time iso8601
local time in the ISO 8601 standard format
$time local
local time in the Common Log Format
3.2.1 Summary
The ngx_stream_access_module module (1.9.2) allows limiting
access to certain client addresses.
server {
...
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
The rules are checked in sequence until the first match is found. In
this example, access is allowed only for IPv4 networks 10.1.1.0/16 and
192.168.1.0/24 excluding the address 192.168.1.1, and for IPv6
network 2001:0db8::/32.
3.2.3 Directives
allow
Syntax: allow address | CIDR | unix: | all;
Default —
Context: stream, server
Allows access for the specified network or address. If the special value
unix: is specified, allows access for all UNIX-domain sockets.
deny
Syntax: deny address | CIDR | unix: | all;
Default —
Context: stream, server
Denies access for the specified network or address. If the special value
unix: is specified, denies access for all UNIX-domain sockets.
3.3.1 Summary
The ngx_stream_geo_module module (1.11.3) creates variables with
values depending on the client IP address.
geo $geo {
default 0;
127.0.0.1 2;
192.168.1.0/24 1;
10.1.0.0/16 1;
::1 2;
2001:0db8::/32 1;
}
3.3.3 Directives
geo
Syntax: geo [$address] $variable { . . . }
Default —
Context: stream
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
connection 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.
The following special parameters are also supported:
delete
deletes the specified network.
default
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.
include
includes a file with addresses and values. There can be several inclusions.
ranges
indicates that addresses are specified as ranges. 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;
127.0.0.0/24 US;
127.0.0.1/32 RU;
10.1.0.0/16 RU;
192.168.1.0/24 UK;
}
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;
}
3.4.1 Summary
The ngx_stream_geoip_module module (1.11.3) creates variables
with values depending on the client IP address, using the precompiled
MaxMind databases.
When using the databases with IPv6 support, IPv4 addresses are looked
up as IPv4-mapped IPv6 addresses.
This module is not built by default, it should be enabled with the
--with-stream_geoip_module configuration parameter.
stream {
geoip_country GeoIP.dat;
geoip_city GeoLiteCity.dat;
3.4.3 Directives
geoip country
Syntax: geoip_country file;
Default —
Context: stream
geoip city
Syntax: geoip_city file;
Default —
Context: stream
geoip org
Syntax: geoip_org file;
Default —
Context: stream
$geoip org
organization name, for example, “The University of Melbourne”.
3.5.1 Summary
The ngx_stream_js_module module is used to implement handlers in
njs — a subset of the JavaScript language.
This module is not built by default. Download and install instructions are
available here.
load_module modules/ngx_stream_js_module.so;
...
stream {
js_include stream.js;
server {
listen 12345;
js_preread qux;
return $foo;
}
server {
listen 12346;
js_access xyz;
proxy_pass 127.0.0.1:8000;
js_filter baz;
}
}
http {
server {
listen 8000;
location / {
return 200 $http_foo\n;
}
}
}
function qux(s) {
var n = s.buffer.indexOf(’\n’);
if (n == -1) {
return s.AGAIN;
}
function foo(s) {
return line;
}
function bar(s) {
var v = s.variables;
s.log("hello from bar() handler!");
return "foo-var" + v.remote_port + "; pid=" + v.pid;
}
function baz(s) {
if (s.fromUpstream || matched) {
return;
}
if (s.remoteAddress.match(’^192.*’)) {
return s.ERROR;
}
var n = req.search(’\n’);
if (n != -1) {
// Inject a new HTTP header.
var rest = req.substr(n + 1);
req = req.substr(0, n + 1);
s.log(’req:’ + req);
s.log(’rest:’ + rest);
function xyz(s) {
if (s.remoteAddress.match(’^192.*’)) {
return s.ABORT;
}
}
3.5.3 Directives
js access
Syntax: js_access function;
Default —
Context: stream, server
js filter
Syntax: js_filter function;
Default —
Context: stream, server
js include
Syntax: js_include file;
Default —
Context: stream
js preread
Syntax: js_preread function;
Default —
Context: stream, server
js set
Syntax: js_set $variable function;
Default —
Context: stream
3.6.1 Summary
The ngx_stream_keyval_module module (1.13.7) creates variables
with values taken from key-value pairs managed by the API.
http {
server {
...
location /api {
api write=on;
}
}
}
stream {
server {
listen 12345 ssl;
proxy_pass $name;
ssl_certificate /usr/local/nginx/conf/cert.pem;
ssl_certificate_key /usr/local/nginx/conf/cert.key;
}
}
3.6.3 Directives
keyval
Syntax: keyval key $variable zone=name;
Default —
Context: stream
Creates a new $variable whose value is looked up by the key in the key-
value database. Strings are matched ignoring the case. The database is stored
in a shared memory zone specified by the zone parameter.
keyval zone
Syntax: keyval_zone zone=name:size [state=file] [timeout=time] [sync];
Default —
Context: stream
Sets the name and size of the shared memory zone that keeps the key-value
database. Key-value pairs are managed by the API.
The optional state parameter specifies a file that keeps the current state
of the key-value database in the JSON format and makes it persistent across
nginx restarts.
The optional timeout parameter (1.15.0) sets the time after which key-
value pairs are removed from the zone.
The optional sync parameter (1.15.0) enables synchronization of the
shared memory zone. The synchronization requires the timeout parameter
to be set.
3.7.1 Summary
The ngx_stream_limit_conn_module module (1.9.3) is used to limit
the number of connections per the defined key, in particular, the number of
connections from a single IP address.
stream {
limit_conn_zone $binary_remote_addr zone=addr:10m;
...
server {
...
limit_conn addr 1;
limit_conn_log_level error;
}
}
3.7.3 Directives
limit conn
Syntax: limit_conn zone number;
Default —
Context: stream, server
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 close the connection. For example, the directives
server {
...
limit_conn addr 1;
}
The directives are inherited from the previous level if and only if there are
no limit_conn directives on the current level.
Sets the desired logging level for cases when the server limits the number
of connections.
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 can contain text, variables, and their combinations (1.11.2). Connections
with an empty key value are not accounted. Usage example:
3.8.1 Summary
The ngx_stream_log_module module (1.11.4) writes session logs in
the specified format.
3.8.3 Directives
access log
Syntax: access_log path format [buffer=size] [gzip[=level]]
[flush=time] [if=condition];
Syntax: access_log off;
Default off
Context: stream, server
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 either the buffer or gzip 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.
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:
For gzip compression to work, nginx must be built with the zlib library.
The file path can contain variables, 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 cache, writing to
the old file can continue during the time specified by the open log file -
cache directive’s valid parameter
The if parameter enables conditional logging. A session will not be logged
if the condition evaluates to “0” or an empty string.
log format
Syntax: log_format name [escape=default|json|none] string . . . ;
Default —
Context: stream
Defines a cache that stores the file descriptors of frequently used logs whose
names contain variables. The directive has the following parameters:
max
sets the maximum number of descriptors in a cache; if the cache becomes
full the least recently used (LRU) descriptors are closed
inactive
sets the time after which the cached descriptor is closed if there were no
access during this time; by default, 10 seconds
min_uses
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
valid
sets the time after which it should be checked that the file still exists
with the same name; by default, 60 seconds
off
disables caching
Usage example:
3.9.1 Summary
The ngx_stream_map_module module (1.11.2) creates variables whose
values depend on values of other variables.
3.9.3 Directives
map
Syntax: map string $variable { . . . }
Default —
Context: stream
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 connection processing.
Parameters inside the map block specify a mapping between source and
resulting values.
Source values are specified as strings or regular expressions.
Strings are matched ignoring the case.
A regular expression 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 that can later
be used in other directives along with the resulting variable.
*.example.com 1;
example.* 1;
example.com 1;
*.example.com 1;
can be combined:
.example.com 1;
5. default value
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.
Sets the maximum size of the map variables hash tables. The details of
setting up hash tables are provided in a separate document.
3.10.1 Summary
The ngx_stream_proxy_module module (1.9.0) allows proxying data
streams over TCP, UDP (1.9.13), and UNIX-domain sockets.
server {
listen 127.0.0.1:12345;
proxy_pass 127.0.0.1:8080;
}
server {
listen 12345;
proxy_connect_timeout 1s;
proxy_timeout 1m;
proxy_pass example.com:12345;
}
server {
listen 53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns.example.com:53;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
3.10.3 Directives
proxy bind
Syntax: proxy_bind address [transparent] | off;
Default —
Context: stream, server
This directive appeared in version 1.9.2.
Sets the size of the buffer used for reading data from the proxied server.
Also sets the size of the buffer used for reading data from the client.
Limits the speed of reading the data from the proxied server. The rate is
specified in bytes per second. The zero value disables rate limiting. The limit
is set per a connection, so if nginx simultaneously opens two connections to
the proxied server, the overall rate will be twice as much as the specified limit.
Limits the time allowed to pass a connection to the next server. The 0
value turns off this limitation.
Limits the number of possible tries for passing a connection to the next
server. The 0 value turns off this limitation.
proxy pass
Syntax: proxy_pass address;
Default —
Context: server
proxy_pass localhost:12345;
proxy_pass unix:/tmp/stream.socket;
proxy_pass $upstream;
In this case, the server name is searched among the described server groups,
and, if not found, is determined using a resolver.
proxy protocol
Syntax: proxy_protocol on | off;
Default off
Context: stream, server
This directive appeared in version 1.9.2.
proxy responses
Syntax: proxy_responses number;
Default —
Context: stream, server
This directive appeared in version 1.9.13.
Sets the number of datagrams expected from the proxied server in response
to a client datagram if the UDP protocol is used. The number serves as a hint
for session termination. By default, the number of datagrams is not limited.
proxy ssl
Syntax: proxy_ssl on | off;
Default off
Context: stream, server
Specifies a file with the certificate in the PEM format used for
authentication to a proxied server.
Specifies a file with the secret key in the PEM format used for
authentication to a proxied server.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify the certificate of the proxied server.
Allows overriding the server name used to verify the certificate of the
proxied server and to be passed through SNI when establishing a connection
with the proxied server. The server name can also be specified using variables
(1.11.3).
By default, the host part of the proxy pass address is used.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Enables or disables passing of the server name through TLS Server Name
Indication extension (SNI, RFC 6066) when establishing a connection with the
proxied server.
proxy timeout
Syntax: proxy_timeout timeout;
Default 10m
Context: stream, server
Sets the timeout between two successive read or write operations on client
or proxied server connections. If no data is transmitted within this time, the
connection is closed.
Limits the speed of reading the data from the client. The rate is specified
in bytes per second. The zero value disables rate limiting. The limit is set per
a connection, so if the client simultaneously opens two connections, the overall
rate will be twice as much as the specified limit.
3.11.1 Summary
The ngx_stream_realip_module module is used to change the client
address and port to the ones sent in the PROXY protocol header (1.11.4). The
PROXY protocol must be previously enabled by setting the proxy protocol
parameter in the listen directive.
This module is not built by default, it should be enabled with the
--with-stream_realip_module configuration parameter.
set_real_ip_from 192.168.1.0/24;
set_real_ip_from 192.168.2.1;
set_real_ip_from 2001:0db8::/32;
3.11.3 Directives
set real ip from
Syntax: set_real_ip_from address | CIDR | unix:;
Default —
Context: stream, server
3.12.1 Summary
The ngx_stream_return_module module (1.11.2) allows sending a
specified value to the client and then closing the connection.
server {
listen 12345;
return $time_iso8601;
}
3.12.3 Directives
return
Syntax: return value;
Default —
Context: server
Specifies a value to send to the client. The value can contain text, variables,
and their combination.
3.13.1 Summary
The ngx_stream_split_clients_module module (1.11.3) creates
variables suitable for A/B testing, also known as split testing.
stream {
...
split_clients "${remote_addr}AAA" $upstream {
0.5% feature_test1;
2.0% feature_test2;
* production;
}
server {
...
proxy_pass $upstream;
}
}
3.13.3 Directives
split clients
Syntax: split_clients string $variable { . . . }
Default —
Context: stream
3.14.1 Summary
The ngx_stream_ssl_module module (1.9.0) provides the necessary
support for a stream proxy server to work with the SSL/TLS protocol.
This module is not built by default, it should be enabled with the
--with-stream_ssl_module configuration parameter.
worker_processes auto;
stream {
...
server {
listen 12345 ssl;
...
}
3.14.3 Directives
ssl certificate
Syntax: ssl_certificate file;
Default —
Context: stream, server
Specifies a file with the certificate in the PEM format for the given 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.
Since version 1.11.0, this directive can be specified multiple times to load
certificates of different types, for example, RSA and ECDSA:
server {
listen 12345 ssl;
ssl_certificate example.com.rsa.crt;
ssl_certificate_key example.com.rsa.key;
ssl_certificate example.com.ecdsa.crt;
ssl_certificate_key example.com.ecdsa.key;
...
}
Specifies a file with the secret key in the PEM format for the given server.
The value engine:name:id can be specified instead of the file, which loads
a secret key with a specified id from the OpenSSL engine name.
ssl ciphers
Syntax: ssl_ciphers ciphers;
Default HIGH:!aNULL:!MD5
Context: stream, 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.
ssl crl
Syntax: ssl_crl file;
Default —
Context: stream, server
This directive appeared in version 1.11.8.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify client certificates.
ssl dhparam
Syntax: ssl_dhparam file;
Default —
Context: stream, server
ssl_ecdh_curve prime256v1:secp384r1;
The special value auto (1.11.0) instructs nginx to use a list built into the
OpenSSL library when using OpenSSL 1.0.2 or higher, or prime256v1 with
older versions.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Example:
stream {
ssl_password_file /etc/keys/global.pass;
...
server {
listen 127.0.0.1:12345;
ssl_certificate_key /etc/keys/first.key;
}
server {
listen 127.0.0.1:12346;
Specifies that server ciphers should be preferred over client ciphers when
the SSLv3 and TLS protocols are used.
ssl protocols
Syntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]
[TLSv1.3];
Default TLSv1 TLSv1.1 TLSv1.2
Context: stream, server
The TLSv1.1 and TLSv1.2 parameters work only when OpenSSL 1.0.1
or higher is used.
The TLSv1.3 parameter (1.13.0) works only when OpenSSL 1.1.1 built
with TLSv1.3 support is used.
Sets the types and sizes of caches that store session parameters. A cache
can be of any of the following types:
off
the use of a session cache is strictly prohibited: nginx explicitly tells a
client that sessions may not be reused.
none
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.
builtin
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.
shared
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 servers.
but using only shared cache without the built-in cache should be more
efficient.
Sets a file with the secret key used to encrypt and decrypt TLS session
tickets. The directive is necessary if the same key has to be shared between
multiple servers. By default, a randomly generated key is used.
If several keys are specified, only the first key is used to encrypt TLS session
tickets. This allows configuring key rotation, for example:
ssl_session_ticket_key current.key;
ssl_session_ticket_key previous.key;
The file must contain 80 or 48 bytes of random data and can be created
using the following command:
Depending on the file size either AES256 (for 80-byte keys, 1.11.8) or
AES128 (for 48-byte keys) is used for encryption.
Specifies a time during which a client may reuse the session parameters.
$ssl cipher
returns the string of ciphers used for an established SSL connection;
$ssl ciphers
returns the list of ciphers supported by the client (1.11.7). Known ciphers
are listed by names, unknown are shown in hexadecimal, for example:
AES128-SHA:AES256-SHA:0x00ff
The variable is fully supported only when using OpenSSL version 1.0.2
or higher. With older versions, the variable is available only for new
sessions and lists only known ciphers.
0x001d:prime256v1:secp521r1:secp384r1
$ssl protocol
returns the protocol of an established SSL connection;
$ssl server name
returns the server name requested through SNI;
$ssl session id
returns the session identifier of an established SSL connection;
$ssl session reused
returns “r” if an SSL session was reused, or “.” otherwise.
3.15.1 Summary
The ngx_stream_ssl_preread_module module (1.11.5) allows
extracting information from the ClientHello message without terminating
SSL/TLS, for example, the sever name requested through SNI or protocols
advertised in ALPN. This module is not built by default, it should be
enabled with the --with-stream_ssl_preread_module configuration
parameter.
upstream backend {
server 192.168.0.1:12345;
server 192.168.0.2:12345;
}
upstream backend2 {
server 192.168.0.3:12345;
server 192.168.0.4:12345;
}
server {
listen 12346;
proxy_pass $name;
ssl_preread on;
}
server {
listen 9000;
proxy_pass $proxy;
ssl_preread on;
}
3.15.3 Directives
ssl preread
Syntax: ssl_preread on | off;
Default off
Context: stream, server
3.16.1 Summary
The ngx_stream_upstream_module module (1.9.0) is used to define
groups of servers that can be referenced by the proxy pass directive.
upstream backend {
hash $remote_addr consistent;
server {
listen 12346;
proxy_pass backend;
}
resolver 10.0.0.1;
upstream dynamic {
zone upstream_dynamic 64k;
server {
listen 12346;
proxy_pass dynamic;
health_check;
}
3.16.3 Directives
upstream
Syntax: upstream name { . . . }
Default —
Context: stream
upstream backend {
server backend1.example.com:12345 weight=5;
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend2;
server backend3.example.com:12345 resolve;
server
Syntax: 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 obligatory port, or as a
UNIX-domain socket path specified after the “unix:” prefix. A domain name
that resolves to several IP addresses defines multiple servers at once.
The following parameters can be defined:
weight=number
sets the weight of the server, by default, 1.
max_conns=number
max_fails=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.
Here, an unsuccessful attempt is an error or timeout while establishing
a connection with the server.
fail_timeout=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.
backup
marks the server as a backup server. Connections to the backup server
will be passed when the primary servers are unavailable.
down
marks the server as permanently unavailable.
Additionally, the following parameters are available as part of our
commercial subscription:
resolve
monitors changes of the IP addresses that correspond to a domain name
of the server, and automatically modifies the upstream configuration
without the need of restarting nginx. The server group must reside in
the shared memory.
In order for this parameter to work, the resolver directive must be
specified in the stream block. Example:
stream {
resolver 10.0.0.1;
upstream u {
zone ...;
...
server example.com:12345 resolve;
}
}
service=name
enables resolving of DNS SRV records and sets the service name (1.9.13).
In order for this parameter to work, it is necessary to specify the resolve
parameter for the server and specify a hostname without a port number.
If the service name does not contain a dot (“.”), then the RFC-compliant
name is constructed and the TCP protocol is added to the service prefix.
For example, to look up the _http._tcp.backend.example.com
SRV record, it is necessary to specify the directive:
If the service name contains one or more dots, then the name is
constructed by joining the service prefix and the server name. For
example, to look up the _http._tcp.backend.example.com and
server1.backend.example.com SRV records, it is necessary to
specify the directives:
The parameter cannot be used along with the hash load balancing
method.
zone
Syntax: zone name [size];
Default —
Context: upstream
Defines the name and size of the shared memory zone that keeps the group’s
configuration and run-time state that are shared between worker processes.
Several groups may share the same zone. In this case, it is enough to specify
the zone size only once.
Prior to version 1.13.3, the configuration was accessible only via a special
location handled by upstream conf.
state
Syntax: state file;
Default —
Context: upstream
This directive appeared in version 1.9.7.
Specifies a file that keeps the state of the dynamically configurable group.
Examples:
The state is currently limited to the list of servers with their parameters.
The file is read when parsing the configuration and is updated each time the
upstream configuration is changed. Changing the file content directly should
be avoided. The directive cannot be used along with the server directive.
hash
Syntax: hash key [consistent];
Default —
Context: upstream
hash $remote_addr;
Note that adding or removing a server from the group may result in
remapping most of the keys to different servers. The method is compatible
with the Cache::Memcached Perl library.
If the consistent parameter is specified, the ketama consistent hashing
method will be used instead. The method ensures that only a few keys will be
remapped to different servers when a server is added to or removed from the
group. This helps to achieve a higher cache hit ratio for caching servers. The
method is compatible with the Cache::Memcached::Fast Perl library with the
ketama points parameter set to 160.
least conn
Syntax: least_conn;
Default —
Context: upstream
Specifies that a server group should use a load balancing method where a
connection 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 in turn using a weighted round-robin balancing method.
least time
Syntax: least_time connect | first_byte | last_byte [inflight];
Default —
Context: upstream
random
Syntax: random [two [method]];
Default —
Context: upstream
This directive appeared in version 1.15.1.
$upstream addr
keeps the IP address and port, or the path to the UNIX-
domain socket of the upstream server (1.11.4). If several servers
were contacted during proxying, their addresses are separated by
commas, e.g. “192.168.1.1:12345, 192.168.1.2:12345,
unix:/tmp/sock”. If a server cannot be selected, the variable keeps
the name of the server group.
$upstream bytes sent
number of bytes sent to an upstream server (1.11.4). Values from several
connections are separated by commas like addresses in the $upstream -
addr variable.
$upstream bytes received
number of bytes received from an upstream server (1.11.4). Values
from several connections are separated by commas like addresses in the
$upstream addr variable.
$upstream connect time
time to connect to the upstream server (1.11.4); the time is kept in
seconds with millisecond resolution. Times of several connections are
separated by commas like addresses in the $upstream addr variable.
$upstream first byte time
time to receive the first byte of data (1.11.4); the time is kept in seconds
with millisecond resolution. Times of several connections are separated
by commas like addresses in the $upstream addr variable.
$upstream session time
session duration in seconds with millisecond resolution (1.11.4). Times
of several connections are separated by commas like addresses in the
$upstream addr variable.
3.17.1 Summary
The ngx_stream_upstream_hc_module module (1.9.0) allows en-
abling periodic health checks of the servers in a group. The server group
must reside in the shared memory.
If a health check fails, the server will be considered unhealthy. 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. Client
connections are not passed to unhealthy servers and servers in the “checking”
state.
upstream tcp {
zone upstream_tcp 64k;
server {
listen 12346;
proxy_pass tcp;
health_check;
}
With this configuration, nginx will check the ability to establish a TCP
connection to each server in the tcp group every five seconds. When a
connection to the server cannot be established, the health check will fail, and
the server will be considered unhealthy.
Health checks can be configured for the UDP protocol:
upstream dns_upstream {
server dns1.example.com:53;
server dns2.example.com:53;
server dns3.example.com:53;
}
server {
listen 53 udp;
proxy_pass dns_upstream;
health_check udp;
}
3.17.3 Directives
health check
Syntax: health_check [parameters];
Default —
Context: server
port=number
defines the port used when connecting to a server to perform a health
check (1.9.7). By default, equals the server port.
udp
specifies that the UDP protocol should be used for health checks instead
of the default TCP protocol (1.9.13).
match
Syntax: match name { . . . }
Default —
Context: stream
Defines the named test set used to verify server responses to health checks.
The following parameters can be configured:
send string;
sends a string to the server;
expect string | ~ regex;
a literal string (1.9.12) or a regular expression that the data obtained
from the server should match. The regular expression is specified with
the preceding “~*” modifier (for case-insensitive matching), or the “~”
modifier (for case-sensitive matching).
Both send and expect parameters can contain hexadecimal literals with the
prefix “\x” followed by two hex digits, for example, “\x80” (1.9.12).
Health check is passed if:
• the TCP connection was successfully established;
• the string from the send parameter, if specified, was sent;
• the data obtained from the server matched the string or regular
expression from the expect parameter, if specified;
• the time elapsed does not exceed the value specified in the health check -
timeout directive.
Example:
upstream backend {
zone upstream_backend 10m;
server 127.0.0.1:12345;
}
match http {
send "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n";
expect ~ "200 OK";
}
server {
listen 12346;
proxy_pass backend;
health_check match=http;
}
Only the first proxy buffer size bytes of data obtained from the server are
examined.
3.18.1 Summary
The ngx_stream_zone_sync_module module (1.13.8) provides the
necessary support for synchronizing contents of shared memory zones between
nodes of a cluster. To enable synchronization for a particular zone, a
corresponding module must support this feature. Currently, it is possible
to synchronize HTTP sticky sessions, information about excessive HTTP
requests, and key-value pairs both in http and stream.
http {
...
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8081;
sticky learn
create=$upstream_cookie_examplecookie
lookup=$cookie_examplecookie
zone=client_sessions:1m sync;
}
...
}
stream {
...
server {
zone_sync;
listen 127.0.0.1:8090;
# cluster of 2 nodes
zone_sync_server a.example.com;
zone_sync_server b.example.com;
A more complex configuration with SSL enabled and with cluster members
defined by DNS:
...
stream {
...
server {
zone_sync;
ssl_certificate localhost.crt;
ssl_certificate_key localhost.key;
zone_sync_ssl on;
zone_sync_ssl_certificate localhost.crt;
zone_sync_ssl_certificate_key localhost.key;
}
}
3.18.3 Directives
zone sync
Syntax: zone_sync;
Default —
Context: server
Sets the number and size of the per-zone buffers used for pushing zone
contents. By default, the buffer size is equal to one memory page. This is
either 4K or 8K, depending on a platform.
socket path specified after the “unix:” prefix. A domain name that resolves
to several IP addresses defines multiple nodes at once.
The resolve parameter instructs nginx to monitor changes of the IP
addresses that correspond to a domain name of the node and automatically
modify the configuration without the need of restarting nginx.
Cluster nodes are specified either dynamically as a single zone_sync_-
server directive with the resolve parameter, or statically as a series of
several directives without the parameter.
In order for the resolve parameter to work, the resolver directive must
be specified in the stream block. Example:
stream {
resolver 10.0.0.1;
server {
zone_sync;
zone_sync_server cluster.example.com resolve;
...
}
}
Specifies a file with the certificate in the PEM format used for
authentication to another cluster server.
Specifies a file with the secret key in the PEM format used for
authentication to another cluster server.
Specifies the enabled ciphers for connections to another cluster server. The
ciphers are specified in the format understood by the OpenSSL library.
The full list can be viewed using the “openssl ciphers” command.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify the certificate of another cluster server.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
4.1.1 Summary
This module is not built by default, it should be enabled with the
--with-mail configuration parameter.
worker_processes 1;
events {
worker_connections 1024;
}
mail {
server_name mail.example.com;
auth_http localhost:9000/cgi-bin/nginxauth.cgi;
417
CHAPTER 4. MAIL SERVER MODULES 4.1. MODULE NGX MAIL CORE MODULE
server {
listen 25;
protocol smtp;
}
server {
listen 110;
protocol pop3;
proxy_pass_error_message on;
}
server {
listen 143;
protocol imap;
}
server {
listen 587;
protocol smtp;
}
}
4.1.3 Directives
listen
Syntax: listen address:port [ssl] [backlog=number] [rcvbuf=size]
[sndbuf=size] [bind] [ipv6only=on|off]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default —
Context: server
Sets the address and port for the socket on which the server will accept
requests. It is possible to specify just the port. The address can also be a
hostname, for example:
listen 127.0.0.1:110;
listen *:110;
listen 110; # same as *:110
listen localhost:110;
listen [::1]:110;
listen [::]:110;
listen unix:/var/run/nginx.sock;
backlog=number
sets the backlog parameter in the listen call that limits the
maximum length for the queue of pending connections (1.9.2). By
default, backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS,
and to 511 on other platforms.
rcvbuf=size
sets the receive buffer size (the SO_RCVBUF option) for the listening
socket (1.11.13).
sndbuf=size
sets the send buffer size (the SO_SNDBUF option) for the listening socket
(1.11.13).
bind
this parameter instructs to make a separate bind call for a given
address:port pair. The fact is that 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 getsockname system
call will be made in this case to determine the address that accepted the
connection. If the ipv6only or so_keepalive parameters are used
then for a given address:port pair a separate bind call will always be
made.
ipv6only=on|off
this parameter 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.
so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]
this parameter 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.
mail
Syntax: mail { . . . }
Default —
Context: main
Provides the configuration file context in which the mail server directives
are specified.
protocol
Syntax: protocol imap | pop3 | smtp;
Default —
Context: server
Sets the protocol for a proxied server. Supported protocols are IMAP,
POP3, and SMTP.
If the directive is not set, the protocol can be detected automatically based
on the well-known port specified in the listen directive:
resolver
Syntax: resolver address . . . [valid=time];
Syntax: resolver off;
Default off
Context: mail, server
Configures name servers used to find the client’s hostname to pass it to the
authentication server, and in the XCLIENT command when proxying SMTP.
For example:
Before version 1.1.9, tuning of caching time was not possible, and nginx
always cached answers for the duration of 5 minutes.
resolver timeout
Syntax: resolver_timeout time;
Default 30s
Context: mail, server
resolver_timeout 5s;
server
Syntax: server { . . . }
Default —
Context: mail
server name
Syntax: server_name name;
Default hostname
Context: mail, server
timeout
Syntax: timeout time;
Default 60s
Context: mail, server
Sets the timeout that is used before proxying to the backend starts.
4.2.1 Directives
auth http
Syntax: auth_http URL;
Default —
Context: mail, server
Sets the URL of the HTTP authentication server. The protocol is described
below.
4.2.2 Protocol
The HTTP protocol is used to communicate with the authentication server.
The data in the response body is ignored, the information is passed only in
the headers.
Examples of requests and responses:
Request:
Good response:
HTTP/1.0 200 OK
Auth-Status: OK
Auth-Server: 198.51.100.1
Auth-Port: 143
Bad response:
HTTP/1.0 200 OK
Auth-Status: Invalid login or password
Auth-Wait: 3
Good response:
HTTP/1.0 200 OK
Auth-Status: OK
Auth-Server: 198.51.100.1
Auth-Port: 143
Auth-Pass: plain-text-pass
HTTP/1.0 200 OK
Auth-Status: Temporary server problem, try again later
Auth-Error-Code: 451 4.3.0
Auth-Wait: 3
If proxying SMTP does not require authentication, the request will look as
follows:
Prior to version 1.11.7, the “FAILED” result did not contain the reason
string.
When the client certificate was present, its details are passed in
the following request headers: Auth-SSL-Subject, Auth-SSL-Issuer,
Auth-SSL-Serial, and Auth-SSL-Fingerprint. If auth http pass -
client cert is enabled, the certificate itself is passed in the Auth-SSL-Cert
header. The request will look as follows:
Auth-Method: plain
Auth-User: user
Auth-Pass: password
Auth-Protocol: imap
Auth-Login-Attempt: 1
Client-IP: 192.0.2.42
Auth-SSL: on
Auth-SSL-Verify: SUCCESS
Auth-SSL-Subject: /CN=example.com
Auth-SSL-Issuer: /CN=example.com
Auth-SSL-Serial: C07AD56B846B5BFF
Auth-SSL-Fingerprint: 29d6a80a123d13355ed16b4b04605e29cb55a5ad
4.3.1 Directives
proxy buffer
Syntax: proxy_buffer size;
Default 4k|8k
Context: mail, server
Sets the size of the buffer used for proxying. By default, the buffer size is
equal to one memory page. Depending on a platform, it is either 4K or 8K.
proxy timeout
Syntax: proxy_timeout timeout;
Default 24h
Context: mail, server
Sets the timeout between two successive read or write operations on client
or proxied server connections. If no data is transmitted within this time, the
connection is closed.
xclient
Syntax: xclient on | off;
Default on
Context: mail, server
• XCLIENT
If the name found by the client IP address points to the same address, it is
passed in the NAME parameter of the XCLIENT command. If the name could
not be found, points to a different address, or resolver is not specified, the
[UNAVAILABLE] is passed in the NAME parameter. If an error has occurred
in the process of resolving, the [TEMPUNAVAIL] value is used.
If XCLIENT is disabled then nginx passes the EHLO command with the
server name when connecting to the backend if the client has passed EHLO, or
HELO with the server name, otherwise.
4.4.1 Summary
The ngx_mail_ssl_module module provides the necessary support for
a mail proxy server to work with the SSL/TLS protocol.
This module is not built by default, it should be enabled with the
--with-mail_ssl_module configuration parameter.
worker_processes auto;
mail {
...
server {
listen 993 ssl;
...
}
4.4.3 Directives
ssl
Syntax: ssl on | off;
Default off
Context: mail, server
This directive was made obsolete in version 1.15.0. The ssl parameter of
the listen directive should be used instead.
ssl certificate
Syntax: ssl_certificate file;
Default —
Context: mail, server
Specifies a file with the certificate in the PEM format for the given 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.
Since version 1.11.0, this directive can be specified multiple times to load
certificates of different types, for example, RSA and ECDSA:
server {
listen 993 ssl;
ssl_certificate example.com.rsa.crt;
ssl_certificate_key example.com.rsa.key;
ssl_certificate example.com.ecdsa.crt;
ssl_certificate_key example.com.ecdsa.key;
...
}
Specifies a file with the secret key in the PEM format for the given server.
The value engine:name:id can be specified instead of the file (1.7.9), which
loads a secret key with a specified id from the OpenSSL engine name.
ssl ciphers
Syntax: ssl_ciphers ciphers;
Default HIGH:!aNULL:!MD5
Context: mail, 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.
ssl crl
Syntax: ssl_crl file;
Default —
Context: mail, server
This directive appeared in version 1.7.11.
Specifies a file with revoked certificates (CRL) in the PEM format used to
verify client certificates.
ssl dhparam
Syntax: ssl_dhparam file;
Default —
Context: mail, server
This directive appeared in version 0.7.2.
ssl_ecdh_curve prime256v1:secp384r1;
The special value auto (1.11.0) instructs nginx to use a list built into the
OpenSSL library when using OpenSSL 1.0.2 or higher, or prime256v1 with
older versions.
Specifies a file with passphrases for secret keys where each passphrase is
specified on a separate line. Passphrases are tried in turn when loading the
key.
Example:
mail {
ssl_password_file /etc/keys/global.pass;
...
server {
server_name mail1.example.com;
ssl_certificate_key /etc/keys/first.key;
}
server {
server_name mail2.example.com;
ssl_certificate_key /etc/keys/second.key;
}
}
Specifies that server ciphers should be preferred over client ciphers when
the SSLv3 and TLS protocols are used.
ssl protocols
Syntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]
[TLSv1.3];
Default TLSv1 TLSv1.1 TLSv1.2
Context: mail, server
The TLSv1.1 and TLSv1.2 parameters (1.1.13, 1.0.12) work only when
OpenSSL 1.0.1 or higher is used.
The TLSv1.3 parameter (1.13.0) works only when OpenSSL 1.1.1 built
with TLSv1.3 support is used.
Sets the types and sizes of caches that store session parameters. A cache
can be of any of the following types:
off
the use of a session cache is strictly prohibited: nginx explicitly tells a
client that sessions may not be reused.
none
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.
builtin
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.
shared
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 servers.
Both cache types can be used simultaneously, for example:
but using only shared cache without the built-in cache should be more
efficient.
Sets a file with the secret key used to encrypt and decrypt TLS session
tickets. The directive is necessary if the same key has to be shared between
multiple servers. By default, a randomly generated key is used.
If several keys are specified, only the first key is used to encrypt TLS session
tickets. This allows configuring key rotation, for example:
ssl_session_ticket_key current.key;
ssl_session_ticket_key previous.key;
The file must contain 80 or 48 bytes of random data and can be created
using the following command:
Depending on the file size either AES256 (for 80-byte keys, 1.11.8) or
AES128 (for 48-byte keys) is used for encryption.
Specifies a time during which a client may reuse the session parameters.
starttls
Syntax: starttls on | off | only;
Default off
Context: mail, server
on
allow usage of the STLS command for the POP3 and the STARTTLS
command for the IMAP and SMTP;
off
deny usage of the STLS and STARTTLS commands;
only
require preliminary TLS transition.
4.5.1 Directives
imap auth
Syntax: imap_auth method . . . ;
Default plain
Context: mail, server
login
AUTH=LOGIN
plain
AUTH=PLAIN
cram-md5
AUTH=CRAM-MD5. In order for this method to work, the password
must be stored unencrypted.
external
AUTH=EXTERNAL (1.11.6).
imap capabilities
Syntax: imap_capabilities extension . . . ;
Default IMAP4 IMAP4rev1 UIDPLUS
Context: mail, server
Sets the IMAP protocol extensions list that is passed to the client
in response to the CAPABILITY command. The authentication methods
specified in the imap auth directive and STARTTLS are automatically added
to this list depending on the starttls directive value.
It makes sense to specify the extensions supported by the IMAP backends to
which the clients are proxied (if these extensions are related to commands used
after the authentication, when nginx transparently proxies a client connection
to the backend).
The current list of standardized extensions is published at www.iana.org.
Sets the size of the buffer used for reading IMAP commands. By default,
the buffer size is equal to one memory page. This is either 4K or 8K, depending
on a platform.
4.6.1 Directives
pop3 auth
Syntax: pop3_auth method . . . ;
Default plain
Context: mail, server
plain
USER/PASS, AUTH PLAIN, AUTH LOGIN. It is not possible to disable
these methods.
apop
APOP. In order for this method to work, the password must be stored
unencrypted.
cram-md5
AUTH CRAM-MD5. In order for this method to work, the password
must be stored unencrypted.
external
AUTH EXTERNAL (1.11.6).
pop3 capabilities
Syntax: pop3_capabilities extension . . . ;
Default TOP USER UIDL
Context: mail, server
Sets the POP3 protocol extensions list that is passed to the client in
response to the CAPA command. The authentication methods specified in
the pop3 auth directive (SASL extension) and STLS are automatically added
to this list depending on the starttls directive value.
It makes sense to specify the extensions supported by the POP3 backends
to which the clients are proxied (if these extensions are related to commands
used after the authentication, when nginx transparently proxies the client
connection to the backend).
The current list of standardized extensions is published at www.iana.org.
4.7.1 Directives
smtp auth
Syntax: smtp_auth method . . . ;
Default login plain
Context: mail, server
login
AUTH LOGIN
plain
AUTH PLAIN
cram-md5
AUTH CRAM-MD5. In order for this method to work, the password
must be stored unencrypted.
external
AUTH EXTERNAL (1.11.6).
none
Authentication is not required.
smtp capabilities
Syntax: smtp_capabilities extension . . . ;
Default —
Context: mail, server
Sets the SMTP protocol extensions list that is passed to the client in
response to the EHLO command. The authentication methods specified in
the smtp auth directive and STARTTLS are automatically added to this list
depending on the starttls directive value.
It makes sense to specify the extensions supported by the MTA to which
the clients are proxied (if these extensions are related to commands used after
the authentication, when nginx transparently proxies the client connection to
the backend).
The current list of standardized extensions is published at www.iana.org.
Sets the size of the buffer used for reading SMTP commands. By default,
the buffer size is equal to one memory page. This is either 4K or 8K, depending
on a platform.
Miscellaneous
441
CHAPTER 5. MISCELLANEOUS 5.1. HIGH AVAILABILITY SUPPORT FOR NGINX PLUS
• IP address of the local and remote nodes (one of which will be configured
as a master, the other one as a backup.
vrrp_script chk_nginx_service {
script "/usr/libexec/keepalived/nginx-ha-check"
interval 3
weight 50
}
vrrp_instance VI_1 {
interface eth0
state BACKUP
priority 101
virtual_router_id 51
advert_int 1
unicast_src_ip 192.168.100.100
unicast_peer {
192.168.100.101
}
authentication {
auth_type PASS
auth_pass f8f0e5114cbe031a3e1e622daf18f82a
}
virtual_ipaddress {
192.168.100.150
}
track_script {
chk_nginx_service
}
notify "/usr/libexec/keepalived/nginx-ha-notify"
}
• Each node in the HA setup needs its own copy of the configuration file,
with values for the priority, unicast_src_ip, and unicast_-
peer directives that are appropriate to the node’s status (master or
backup).
• The priority of the first node (which has a base priority of 101) is set to
151.
• The priority of the second node (which has a base priority of 100) is set
to 150.
The first node has higher priority (151 in this case) and becomes master.
Use the interval directive to specify how often the check script executes, in
seconds (it is set to 3 in the default configuration). Note that the check also
fails when the timeout is reached (by default, the timeout is the same as the
check interval).
Use the rise and fall directives to specify how many times the script
must succeed or fail before action is taken (they are not set in the default
configuration).
The default script provided with the nginx-ha-keepalived package
checks if nginx is up. We recommend creating additional scripts as appropriate
for your local setup.
virtual_ipaddress {
192.168.100.150
192.168.100.200
1234:5678:9abc:def::1/64
}
Feb 27 14:42:04 centos7-1 systemd: Starting LVS and VRRP High Availability
Monitor...
Feb 27 14:42:04 centos7-1 Keepalived[19242]: Starting Keepalived v1.2.15
(02/26,2015)
Feb 27 14:42:04 centos7-1 Keepalived[19243]: Starting VRRP child process, pid
=19244
Feb 27 14:42:04 centos7-1 Keepalived_vrrp[19244]: Registering Kernel netlink
reflector
Feb 27 14:42:04 centos7-1 Keepalived_vrrp[19244]: Registering Kernel netlink
command channel
Feb 27 14:42:04 centos7-1 Keepalived_vrrp[19244]: Registering gratuitous ARP
shared channel
Feb 27 14:42:05 centos7-1 systemd: Started LVS and VRRP High Availability
Monitor.
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: Opening file ’/etc/keepalived
/keepalived.conf’.
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: Truncating auth_pass to 8
characters
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: Configuration is using :
64631 Bytes
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: Using LinkWatch kernel
netlink reflector...
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1) Entering
BACKUP STATE
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: VRRP sockpool: [ifindex(2),
proto(112), unicast(1), fd(14,15)]
Feb 27 14:42:05 centos7-1 nginx-ha-keepalived: Transition to state ’BACKUP’ on
VRRP instance ’VI_1’.
Feb 27 14:42:05 centos7-1 Keepalived_vrrp[19244]: VRRP_Script(chk_nginx_service
) succeeded
Feb 27 14:42:06 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1) forcing a
new MASTER election
Feb 27 14:42:06 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1) forcing a
new MASTER election
Feb 27 14:42:07 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1)
Transition to MASTER STATE
Feb 27 14:42:08 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1) Entering
MASTER STATE
Feb 27 14:42:08 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1) setting
protocol VIPs.
Feb 27 14:42:08 centos7-1 Keepalived_vrrp[19244]: VRRP_Instance(VI_1) Sending
gratuitous ARPs on eth0 for 192.168.100.150
Feb 27 14:42:08 centos7-1 nginx-ha-keepalived: Transition to state ’MASTER’ on
VRRP instance ’VI_1’.
If the system log does not explain the source of a problem, run the tcpdump
command with the following parameters to display the VRRP advertisements
that are sent on the local network:
If you have multiple VRRP instances on the local network and want to
filter the traffic for select hosts, include the host parameter to specify the
IP address that is defined in the unicast_peer block, as in the following
example:
centos7-1 # tcpdump -vvv -ni eth0 proto vrrp and host 192.168.100.101
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 65535
bytes
14:48:27.188100 IP (tos 0xc0, ttl 255, id 382, offset 0, flags [none], proto
VRRP (112), length 40)
192.168.100.100 > 192.168.100.101: vrrp 192.168.100.100 > 192.168.100.101:
VRRPv2, Advertisement, vrid 51, prio 151, authtype simple, intvl 1s,
length 20, addrs: 192.168.100.150 auth "f8f0e511"
5.1.8 Miscellaneous
Note that NGINX configuration files on both nodes must define the services
that are being made highly available. Keeping the configuration files in sync
is outside the scope of the provided clustering software.
The nginx-ha-keepalived package comes with numerous configura-
tion examples, in the /usr/share/doc/nginx-ha-keepalived/ direc-
tory. They show how to configure numerous aspects of an HA setup.
5.2.1 Overview
nginx supports the following command-line parameters:
• -p prefix — set nginx path prefix, i.e. a directory that will keep
server files (default value is /usr/local/nginx).
This appendix contains the most important changes that may apply to both NGINX Plus
and nginx/OSS. Full changelog for nginx/OSS is available in the packages and by the
following link: http://nginx.org/en/CHANGES
448
APPENDIX A. CHANGELOG FOR NGINX PLUS
Legal Notices
Open source components included in the NGINX Plus (package name is nginx-plus) are:
• nginx/OSS (1.15.2), distributed under 2-clause BSD license.
http://nginx.org/
1. Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
• Internal MD5 implementation (used only if no system MD5 support was found),
based on Alexander Peslyak’s public domain implementation:
This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
MD5 Message-Digest Algorithm (RFC 1321).
Homepage:
http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
Author: Alexander Peslyak, better known as Solar Designer <solar at
openwall.com>
This software was written by Alexander Peslyak in 2001. No copyright is claimed,
and the software is hereby placed in the public domain. In case this attempt to
disclaim copyright and place the software in the public domain is deemed null and
void, then the software is Copyright © 2001 Alexander Peslyak and it is hereby
released to the general public under the following terms:
455
APPENDIX B. LEGAL NOTICES
– The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ”AS IS”, WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
• history, manage session history with JavaScript (4.7.2), distributed under MIT
license.
https://github.com/ReactTraining/history
• preact, fast 3kb React alternative with the same ES6 API (8.2.6), distributed under
MIT license.
https://github.com/developit/preact
• webpack, a bundler for javascript and friends (3.9.1), distributed under MIT license.
https://github.com/webpack/webpack
• npm-font-open-sans, Open Sans font family - incl. usage of CSS, SCSS, LESS
(1.1.0), distributed under Apache 2.0 license.
https://github.com/dasrick/npm-font-open-sans
The following component (Swagger UI) is distributed as a set of standalone files in the
/usr/share/nginx/html/swagger-ui directory:
• Swagger UI (3.5.0), distributed under Apache 2.0 license.
https://github.com/swagger-api/swagger-ui
Copyright 2017 SmartBear Software
Licensed under the Apache License, Version 2.0 (the ”License”); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an ”AS IS” BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
Optional add-on and third-party modules provided with NGINX Plus may include
additional open-source components. The licenses for these components are included in the
installation package for each module.
460
INDEX INDEX
server, 46, 300, 357, 401, 421 ssl stapling responder, 280
server name, 46, 421 ssl stapling verify, 280
server name in redirect, 48 ssl trusted certificate, 281, 395, 434
server names hash bucket size, 48 ssl verify client, 281, 396, 434
server names hash max size, 48 ssl verify depth, 281, 396, 434
server tokens, 48 starttls, 434
session log, 262 state, 303, 404
session log format, 262 status, 286
session log zone, 263 status format, 286
set, 239 status zone, 63, 287
set real ip from, 231, 387 sticky, 309
slice, 264 sticky cookie insert, 312
smtp auth, 439 stream, 358
smtp capabilities, 439 stub status, 295
smtp client buffer, 440 sub filter, 297
smtp greeting delay, 440 sub filter last modified, 297
source charset, 110 sub filter once, 298
split clients, 266, 389 sub filter types, 298
ssi, 267 subrequest output buffer size, 49
ssi last modified, 267
ssi min file chunk, 268 tcp nodelay, 49, 358
ssi silent errors, 268 tcp nopush, 49
ssi types, 268 thread pool, 12
ssi value length, 268 timeout, 421
ssl, 274, 429 timer resolution, 12
ssl buffer size, 274 try files, 49
ssl certificate, 275, 391, 429 types, 51
ssl certificate key, 275, 391, 430 types hash bucket size, 52
ssl ciphers, 275, 392, 430 types hash max size, 52
ssl client certificate, 276, 392, 430 underscores in headers, 52
ssl crl, 276, 392, 430 uninitialized variable warn, 239
ssl dhparam, 276, 392, 431 upstream, 300, 401
ssl early data, 276 upstream conf, 314
ssl ecdh curve, 277, 392, 431 use, 12
ssl engine, 11 user, 13
ssl handshake timeout, 393 userid, 322
ssl password file, 277, 393, 431 userid domain, 323
ssl prefer server ciphers, 277, 393, 432 userid expires, 323
ssl preread, 399 userid mark, 323
ssl protocols, 278, 394, 432 userid name, 323
ssl session cache, 278, 394, 432 userid p3p, 324
ssl session ticket key, 279, 395, 433 userid path, 324
ssl session tickets, 279, 395, 433 userid service, 324
ssl session timeout, 279, 395, 433 uwsgi bind, 326
ssl stapling, 279 uwsgi buffer size, 327
ssl stapling file, 280 uwsgi buffering, 327