Directives
Syntax: |
absolute_redirect
|
---|---|
Default: |
absolute_redirect on; |
Context: |
http , server , location
|
This directive appeared in version 1.11.8.
If disabled, redirects issued by nginx will be relative.
See also server_name_in_redirect
and port_in_redirect directives.
Syntax: |
aio
|
---|---|
Default: |
aio 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; }
On FreeBSD, AIO can be used starting from FreeBSD 4.3.
Prior to FreeBSD 11.0,
AIO can either be linked statically into a kernel:
options VFS_AIO
or loaded dynamically as a kernel loadable module:
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;
By default, multi-threading is disabled, it should be
enabled with the
--with-threads
configuration parameter.
Currently, multi-threading is compatible only with the
epoll,
kqueue,
and
eventport methods.
Multi-threaded sending of files is only supported on Linux.
See also the sendfile directive.
Syntax: |
aio_write
|
---|---|
Default: |
aio_write off; |
Context: |
http , server , location
|
This directive appeared in version 1.9.13.
If aio is enabled, specifies whether it is used for writing files.
Currently, this only works when using
aio threads
and is limited to writing temporary files
with data received from proxied servers.
Syntax: |
alias
|
---|---|
Default: |
— |
Context: |
location
|
Defines a replacement for the specified location.
For example, with the following configuration
location /i/ { alias /data/w3/images/; }
on request of
“/i/top.gif
”, the file
/data/w3/images/top.gif
will be sent.
The path
value can contain variables,
except $document_root
and $realpath_root
.
If alias
is used inside a location defined
with a regular expression then such regular expression should
contain captures and alias
should refer to
these captures (0.7.40), for example:
location ~ ^/users/(.+.(?:gif|jpe?g|png))$ { alias /data/w3/images/$1; }
When location matches the last part of the directive’s value:
location /images/ { alias /data/w3/images/; }
it is better to use the
root
directive instead:
location /images/ { root /data/w3; }
Syntax: |
auth_delay
|
---|---|
Default: |
auth_delay 0s; |
Context: |
http , server , location
|
This directive appeared in version 1.17.10.
Delays processing of unauthorized requests with 401 response code
to prevent timing attacks when access is limited by
password, by the
result of subrequest,
or by JWT.
Syntax: |
chunked_transfer_encoding
|
---|---|
Default: |
chunked_transfer_encoding on; |
Context: |
http , server , location
|
Allows disabling chunked transfer encoding in HTTP/1.1.
It may come in handy when using a software failing to support
chunked encoding despite the standard’s requirement.
Syntax: |
client_body_buffer_size
|
---|---|
Default: |
client_body_buffer_size 8k|16k; |
Context: |
http , server , location
|
Sets buffer size for reading client request body.
In case the request body is larger than the buffer,
the whole body or only its part is written to a
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.
Syntax: |
client_body_in_file_only
|
---|---|
Default: |
client_body_in_file_only off; |
Context: |
http , server , location
|
Determines whether nginx should save the entire client request body
into a file.
This directive can be used during debugging, or when using the
$request_body_file
variable, or the
$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.
Syntax: |
client_body_in_single_buffer
|
---|---|
Default: |
client_body_in_single_buffer off; |
Context: |
http , server , location
|
Determines whether nginx should save the entire client request body
in a single buffer.
The directive is recommended when using the
$request_body
variable, to save the number of copy operations involved.
Syntax: |
client_body_temp_path
|
---|---|
Default: |
client_body_temp_path client_body_temp; |
Context: |
http , server , location
|
Defines a directory for storing temporary files holding client request bodies.
Up to three-level subdirectory hierarchy can be used under the specified
directory.
For example, in the following configuration
client_body_temp_path /spool/nginx/client_temp 1 2;
a path to a temporary file might look like this:
/spool/nginx/client_temp/7/45/00000123457
Syntax: |
client_body_timeout
|
---|---|
Default: |
client_body_timeout 60s; |
Context: |
http , server , location
|
Defines a timeout for reading client request body.
The timeout is set only for a period between two successive read operations,
not for the transmission of the whole request body.
If a client does not transmit anything within this time, the
request is terminated with the
408 (Request Time-out)
error.
Syntax: |
client_header_buffer_size
|
---|---|
Default: |
client_header_buffer_size 1k; |
Context: |
http , server
|
Sets buffer size for reading client request header.
For most requests, a buffer of 1K bytes is enough.
However, if a request includes long cookies, or comes from a WAP client,
it may not fit into 1K.
If a request line or a request header field does not fit into
this buffer then larger buffers, configured by the
large_client_header_buffers directive,
are allocated.
If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.
Syntax: |
client_header_timeout
|
---|---|
Default: |
client_header_timeout 60s; |
Context: |
http , server
|
Defines a timeout for reading client request header.
If a client does not transmit the entire header within this time, the
request is terminated with the
408 (Request Time-out)
error.
Syntax: |
client_max_body_size
|
---|---|
Default: |
client_max_body_size 1m; |
Context: |
http , server , location
|
Sets the maximum allowed size of the client request body.
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.
Syntax: |
connection_pool_size
|
---|---|
Default: |
connection_pool_size 256|512; |
Context: |
http , server
|
Allows accurate tuning of per-connection memory allocations.
This directive has minimal impact on performance
and should not generally be used.
By default, the size is equal to
256 bytes on 32-bit platforms and 512 bytes on 64-bit platforms.
Prior to version 1.9.8, the default value was 256 on all platforms.
Syntax: |
default_type
|
---|---|
Default: |
default_type text/plain; |
Context: |
http , server , location
|
Defines the default MIME type of a response.
Mapping of file name extensions to MIME types can be set
with the types directive.
Syntax: |
directio
|
---|---|
Default: |
directio 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;
or when using aio on Linux.
Syntax: |
directio_alignment
|
---|---|
Default: |
directio_alignment 512; |
Context: |
http , server , location
|
This directive appeared in version 0.8.11.
Sets the alignment for
directio.
In most cases, a 512-byte alignment is enough.
However, when using XFS under Linux, it needs to be increased to 4K.
Syntax: |
disable_symlinks disable_symlinks
|
---|---|
Default: |
disable_symlinks off; |
Context: |
http , server , location
|
This directive appeared in version 1.1.15.
Determines how symbolic links should be treated when opening files:
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
(parameterson
andif_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.
On systems that do not support opening of directories only for search,
to use these parameters it is required that worker processes
have read permissions for all directories being checked.
The
ngx_http_autoindex_module,
ngx_http_random_index_module,
and ngx_http_dav_module
modules currently ignore this directive.
Syntax: |
error_page
|
---|---|
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:
error_page 404 /404.html; error_page 500 502 503 504 /50x.html;
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
”).
Furthermore, it is possible to change the response code to another
using the “=
response
” syntax, for example:
error_page 404 =200 /empty.gif;
If an error response is processed by a proxied server
or a FastCGI/uwsgi/SCGI/gRPC server,
and the server may return different response codes (e.g., 200, 302, 401
or 404), it is possible to respond with the code it returns:
error_page 404 = /404.php;
If there is no need to change URI and method during internal redirection
it is possible to pass error processing into a named location:
location / { error_page 404 = @fallback; } location @fallback { proxy_pass http://backend; }
If
uri
processing leads to an error,
the status code of the last occurred error is returned to the client.
It is also possible to use URL redirects for error processing:
error_page 403 http://example.com/forbidden.html; error_page 404 =301 http://example.com/notfound.html;
In this case, by default, the response code 302 is returned to the client.
It can only be changed to one of the redirect status
codes (301, 302, 303, 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 configuration level
if and only if there are no error_page
directives
defined on the current level.
Syntax: |
etag
|
---|---|
Default: |
etag on; |
Context: |
http , server , location
|
This directive appeared in version 1.3.3.
Enables or disables automatic generation of the “ETag”
response header field for static resources.
Syntax: |
http { ... }
|
---|---|
Default: |
— |
Context: |
main
|
Provides the configuration file context in which the HTTP server directives
are specified.
Syntax: |
if_modified_since
|
---|---|
Default: |
if_modified_since exact; |
Context: |
http , server , location
|
This directive appeared in version 0.7.24.
Specifies how to compare modification time of a response
with the time in the
“If-Modified-Since”
request header field:
off
- the response is always considered modified (0.7.34);
exact
- exact match;
before
-
modification time of the response is
less than or equal to the time in the “If-Modified-Since”
request header field.
Syntax: |
ignore_invalid_headers
|
---|---|
Default: |
ignore_invalid_headers on; |
Context: |
http , server
|
Controls whether header fields with invalid names should be ignored.
Valid names are composed of English letters, digits, hyphens, and possibly
underscores (as controlled by the underscores_in_headers
directive).
If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.
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; -
requests redirected by the “X-Accel-Redirect”
response header field from an upstream server; -
subrequests formed by the
“include virtual
”
command of the
ngx_http_ssi_module
module, by the
ngx_http_addition_module
module directives, and by
auth_request and
mirror directives; -
requests changed by the
rewrite directive.
Example:
error_page 404 /404.html; location = /404.html { internal; }
There is a limit of 10 internal redirects per request to prevent
request processing cycles that can occur in incorrect configurations.
If this limit is reached, the error
500 (Internal Server Error) is returned.
In such cases, the “rewrite or internal redirection cycle” message
can be seen in the error log.
Syntax: |
keepalive_disable
|
---|---|
Default: |
keepalive_disable msie6; |
Context: |
http , server , location
|
Disables keep-alive connections with misbehaving browsers.
The browser
parameters specify which
browsers will be affected.
The value msie6
disables keep-alive connections
with old versions of MSIE, once a POST request is received.
The value safari
disables keep-alive connections
with Safari and Safari-like browsers on macOS and macOS-like
operating systems.
The value none
enables keep-alive connections
with all browsers.
Prior to version 1.1.18, the value
safari
matched
all Safari and Safari-like browsers on all operating systems, and
keep-alive connections with them were disabled by default.
Syntax: |
keepalive_requests
|
---|---|
Default: |
keepalive_requests 1000; |
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.
Closing connections periodically is necessary to free
per-connection memory allocations.
Therefore, using too high maximum number of requests
could result in excessive memory usage and not recommended.
Prior to version 1.19.10, the default value was 100.
Syntax: |
keepalive_time
|
---|---|
Default: |
keepalive_time 1h; |
Context: |
http , server , location
|
This directive appeared in version 1.19.10.
Limits the maximum time during which
requests can be processed through one keep-alive connection.
After this time is reached, the connection is closed
following the subsequent request processing.
Syntax: |
keepalive_timeout
|
---|---|
Default: |
keepalive_timeout 75s; |
Context: |
http , server , location
|
The first parameter sets a timeout during which a keep-alive
client connection will stay open on the server side.
The zero value disables keep-alive client connections.
The optional second parameter sets a value in the
“Keep-Alive: timeout=time
”
response header field.
Two parameters may differ.
The
“Keep-Alive: timeout=time
”
header field is recognized by Mozilla and Konqueror.
MSIE closes keep-alive connections by itself in about 60 seconds.
Syntax: |
large_client_header_buffers
|
---|---|
Default: |
large_client_header_buffers 4 8k; |
Context: |
http , server
|
Sets the maximum number
and size
of
buffers used for reading large client request header.
A request line cannot exceed the size of one buffer, or the
414 (Request-URI Too Large)
error is returned to the client.
A request header field cannot exceed the size of one buffer as well, or the
400 (Bad Request)
error is returned to the client.
Buffers are allocated only on demand.
By default, the buffer size is equal to 8K bytes.
If after the end of request processing a connection is transitioned
into the keep-alive state, these buffers are released.
If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.
Syntax: |
limit_except
|
---|---|
Default: |
— |
Context: |
location
|
Limits allowed HTTP methods inside a location.
The method
parameter can be one of the following:
GET
,
HEAD
,
POST
,
PUT
,
DELETE
,
MKCOL
,
COPY
,
MOVE
,
OPTIONS
,
PROPFIND
,
PROPPATCH
,
LOCK
,
UNLOCK
,
or
PATCH
.
Allowing the GET
method makes the
HEAD
method also allowed.
Access to other methods can be limited using the
ngx_http_access_module,
ngx_http_auth_basic_module,
and
ngx_http_auth_jwt_module
(1.13.10)
modules directives:
limit_except GET { allow 192.168.1.0/32; deny all; }
Please note that this will limit access to all methods
except GET and HEAD.
Syntax: |
limit_rate
|
---|---|
Default: |
limit_rate 0; |
Context: |
http , server , location , if in location
|
Limits the rate of response transmission to a client.
The rate
is specified in bytes per second.
The zero value disables rate limiting.
The limit is set per a request, and so if a client simultaneously opens
two connections, the overall rate will be twice as much
as the specified limit.
Parameter value can contain variables (1.17.0).
It may be useful in cases where rate should be limited
depending on a certain condition:
map $slow $rate { 1 4k; 2 8k; } limit_rate $rate;
Rate limit can also be set in the
$limit_rate
variable,
however, since version 1.17.0, this method is not recommended:
server { if ($slow) { set $limit_rate 4k; } ... }
Rate limit can also be set in the
“X-Accel-Limit-Rate” header field of a proxied server response.
This capability can be disabled using the
proxy_ignore_headers,
fastcgi_ignore_headers,
uwsgi_ignore_headers,
and
scgi_ignore_headers
directives.
Syntax: |
limit_rate_after
|
---|---|
Default: |
limit_rate_after 0; |
Context: |
http , server , location , if in location
|
This directive appeared in version 0.8.0.
Sets the initial amount after which the further transmission
of a response to a client will be rate limited.
Parameter value can contain variables (1.17.0).
Example:
location /flv/ { flv; limit_rate_after 500k; limit_rate 50k; }
Syntax: |
lingering_close
|
---|---|
Default: |
lingering_close on; |
Context: |
http , server , location
|
This directive appeared in versions 1.1.0 and 1.0.6.
Controls how nginx closes client connections.
The default value “on
” instructs nginx to
wait for and
process additional data from a client
before fully closing a connection, but only
if heuristics suggests that a client may be sending more data.
The value “always
” will cause nginx to unconditionally
wait for and process additional client data.
The value “off
” tells nginx to never wait for
more data and close the connection immediately.
This behavior breaks the protocol and should not be used under normal
circumstances.
To control closing
HTTP/2 connections,
the directive must be specified on the server level (1.19.1).
Syntax: |
lingering_time
|
---|---|
Default: |
lingering_time 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.
Syntax: |
lingering_timeout
|
---|---|
Default: |
lingering_timeout 5s; |
Context: |
http , server , location
|
When lingering_close is in effect, this directive specifies
the maximum waiting time for more client data to arrive.
If data are not received during this time, the connection is closed.
Otherwise, the data are read and ignored, and nginx starts waiting
for more data again.
The “wait-read-ignore” cycle is repeated, but no longer than specified by the
lingering_time directive.
Syntax: |
listen listen listen
|
---|---|
Default: |
listen *:80 | *:8000; |
Context: |
server
|
Sets the address
and port
for IP,
or the path
for a UNIX-domain socket on which
the server will accept requests.
Both address
and port
,
or only address
or only port
can be specified.
An address
may also be a hostname, for example:
listen 127.0.0.1:8000; listen 127.0.0.1; listen 8000; listen *:8000; listen localhost:8000;
IPv6 addresses (0.7.36) are specified in square brackets:
listen [::]:8000; listen [::1];
UNIX-domain sockets (0.8.21) are specified with the “unix:
”
prefix:
listen unix:/var/run/nginx.sock;
If only address
is given, the port 80 is used.
If the directive is not present then either *:80
is used
if nginx runs with the superuser privileges, or *:8000
otherwise.
The default_server
parameter, if present,
will cause the server to become the default server for the specified
address
:port
pair.
If none of the directives have the default_server
parameter then the first server with the
address
:port
pair will be
the default server for this pair.
In versions prior to 0.8.21 this parameter is named simply
default
.
The ssl
parameter (0.7.14) allows specifying that all
connections accepted on this port should work in SSL mode.
This allows for a more compact configuration for the server that
handles both HTTP and HTTPS requests.
The http2
parameter (1.9.5) configures the port to accept
HTTP/2 connections.
Normally, for this to work the ssl
parameter should be
specified as well, but nginx can also be configured to accept HTTP/2
connections without SSL.
The spdy
parameter (1.3.15-1.9.4) allows accepting
SPDY connections on this port.
Normally, for this to work the ssl
parameter should be
specified as well, but nginx can also be configured to accept SPDY
connections without SSL.
The proxy_protocol
parameter (1.5.12)
allows specifying that all connections accepted on this port should use the
PROXY
protocol.
The PROXY protocol version 2 is supported since version 1.13.11.
The listen
directive
can have several additional parameters specific to socket-related system calls.
These parameters can be specified in any
listen
directive, but only once for a given
address
:port
pair.
In versions prior to 0.8.21, they could only be
specified in thelisten
directive together with the
default
parameter.
-
setfib
=number
-
this parameter (0.8.44) sets the associated routing table, FIB
(theSO_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 thesame 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
(theSO_RCVBUF
option) for the listening socket. -
sndbuf
=size
-
sets the send buffer size
(theSO_SNDBUF
option) for the listening socket. -
accept_filter
=filter
-
sets the name of accept filter
(theSO_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()
(theTCP_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 severallisten
directives with the same port but different addresses, and one of the
listen
directives listens on all addresses
for the given port (*:
port
), nginx
willbind()
only to*:
port
.
It should be noted that thegetsockname()
system call will be
made in this case to determine the address that accepted the connection.
If thesetfib
,
fastopen
,
backlog
,rcvbuf
,
sndbuf
,accept_filter
,
deferred
,ipv6only
,
reuseport
,
orso_keepalive
parameters
are used then for a given
address
:port
pair
a separatebind()
call will always be made. -
ipv6only
=on
|off
-
this parameter (0.7.42) determines
(via theIPV6_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,
orSO_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).Inappropriate use of this option may have its security
implications. -
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 theTCP_KEEPIDLE
,
TCP_KEEPINTVL
, andTCP_KEEPCNT
socket options.
On such systems (currently, Linux 2.4+, NetBSD 5+, and
FreeBSD 9.0-STABLE), they can be configured
using thekeepidle
,keepintvl
, and
keepcnt
parameters.
One or two parameters may be omitted, in which case the system default setting
for the corresponding socket option will be in effect.
For example,so_keepalive=30m::10
will set the idle timeout (
TCP_KEEPIDLE
) to 30 minutes,
leave the probe interval (TCP_KEEPINTVL
) at its system default,
and set the probes count (TCP_KEEPCNT
) to 10 probes.
Example:
listen 127.0.0.1 default_server accept_filter=dataready backlog=1024;
Syntax: |
location [ location
|
---|---|
Default: |
— |
Context: |
server , location
|
Sets configuration depending on a request URI.
The matching is performed against a normalized URI,
after decoding the text encoded in the “%XX
” form,
resolving references to relative path components “.
”
and “..
”, and possible
compression of two or more
adjacent slashes into a single slash.
A location can either be defined by a prefix string, or by a regular expression.
Regular expressions are specified with the preceding
“~*
” modifier (for case-insensitive matching), or the
“~
” modifier (for case-sensitive matching).
To find location matching a given request, nginx first checks
locations defined using the prefix strings (prefix locations).
Among them, the location with the longest matching
prefix is selected and remembered.
Then regular expressions are checked, in the order of their appearance
in the configuration file.
The search of regular expressions terminates on the first match,
and the corresponding configuration is used.
If no match with a regular expression is found then the
configuration of the prefix location remembered earlier is used.
location
blocks can be nested, with some exceptions
mentioned below.
For case-insensitive operating systems such as macOS and Cygwin,
matching with prefix strings ignores a case (0.7.7).
However, comparison is limited to one-byte locales.
Regular expressions can contain captures (0.7.40) that can later
be used in other directives.
If the longest matching prefix location has the “^~
” modifier
then regular expressions are not checked.
Also, using the “=
” modifier it is possible to define
an exact match of URI and location.
If an exact match is found, the search terminates.
For example, if a “/
” request happens frequently,
defining “location = /
” will speed up the processing
of these requests, as search terminates right after the first
comparison.
Such a location cannot obviously contain nested locations.
In versions from 0.7.1 to 0.8.41, if a request matched the prefix
location without the “=
” and “^~
”
modifiers, the search also terminated and regular expressions were
not checked.
Let’s illustrate the above by an example:
location = / { [ configuration A ] } location / { [ configuration B ] } location /documents/ { [ configuration C ] } location ^~ /images/ { [ configuration D ] } location ~* .(gif|jpg|jpeg)$ { [ configuration E ] }
The “/
” request will match configuration A,
the “/index.html
” request will match configuration B,
the “/documents/document.html
” request will match
configuration C,
the “/images/1.gif
” request will match configuration D, and
the “/documents/1.jpg
” request will match configuration E.
The “@
” prefix defines a named location.
Such a location is not used for a regular request processing, but instead
used for request redirection.
They cannot be nested, and cannot contain nested locations.
If a location is defined by a prefix string that ends with the slash character,
and requests are processed by one of
proxy_pass,
fastcgi_pass,
uwsgi_pass,
scgi_pass,
memcached_pass, or
grpc_pass,
then the special processing is performed.
In response to a request with URI equal to this string,
but without the trailing slash,
a permanent redirect with the code 301 will be returned to the requested URI
with the slash appended.
If this is not desired, an exact match of the URI and location could be
defined like this:
location /user/ { proxy_pass http://user.example.com; } location = /user { proxy_pass http://login.example.com; }
Syntax: |
log_not_found
|
---|---|
Default: |
log_not_found on; |
Context: |
http , server , location
|
Enables or disables logging of errors about not found files into
error_log.
Syntax: |
log_subrequest
|
---|---|
Default: |
log_subrequest off; |
Context: |
http , server , location
|
Enables or disables logging of subrequests into
access_log.
Syntax: |
max_ranges
|
---|---|
Default: |
— |
Context: |
http , server , location
|
This directive appeared in version 1.1.2.
Limits the maximum allowed number of ranges in byte-range requests.
Requests that exceed the limit are processed as if there were no
byte ranges specified.
By default, the number of ranges is not limited.
The zero value disables the byte-range support completely.
Syntax: |
merge_slashes
|
---|---|
Default: |
merge_slashes on; |
Context: |
http , server
|
Enables or disables compression of two or more adjacent slashes
in a URI into a single slash.
Note that compression is essential for the correct matching of prefix string
and regular expression locations.
Without it, the “//scripts/one.php
” request would not match
location /scripts/ { ... }
and might be processed as a static file.
So it gets converted to “/scripts/one.php
”.
Turning the compression off
can become necessary if a URI
contains base64-encoded names, since base64 uses the “/
”
character internally.
However, for security considerations, it is better to avoid turning
the compression off.
If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.
Syntax: |
msie_padding
|
---|---|
Default: |
msie_padding on; |
Context: |
http , server , location
|
Enables or disables adding comments to responses for MSIE clients with status
greater than 400 to increase the response size to 512 bytes.
Syntax: |
msie_refresh
|
---|---|
Default: |
msie_refresh off; |
Context: |
http , server , location
|
Enables or disables issuing refreshes instead of redirects for MSIE clients.
Syntax: |
open_file_cache open_file_cache
|
---|---|
Default: |
open_file_cache off; |
Context: |
http , server , location
|
Configures a cache that can store:
- open file descriptors, their sizes and modification times;
- information on existence of directories;
-
file lookup errors, such as “file not found”, “no read permission”,
and so on.Caching of errors should be enabled separately by the
open_file_cache_errors
directive.
The directive has the following parameters:
-
max
-
sets the maximum number of elements in the cache;
on cache overflow the least recently used (LRU) elements are removed; -
inactive
-
defines a time after which an element is removed from the cache
if it has not been accessed during this time;
by default, it is 60 seconds; -
off
- disables the cache.
Example:
open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;
Syntax: |
open_file_cache_errors
|
---|---|
Default: |
open_file_cache_errors off; |
Context: |
http , server , location
|
Enables or disables caching of file lookup errors by
open_file_cache.
Syntax: |
open_file_cache_min_uses
|
---|---|
Default: |
open_file_cache_min_uses 1; |
Context: |
http , server , location
|
Sets the minimum number
of file accesses during
the period configured by the inactive
parameter
of the open_file_cache directive, required for a file
descriptor to remain open in the cache.
Syntax: |
open_file_cache_valid
|
---|---|
Default: |
open_file_cache_valid 60s; |
Context: |
http , server , location
|
Sets a time after which
open_file_cache
elements should be validated.
Syntax: |
output_buffers
|
---|---|
Default: |
output_buffers 2 32k; |
Context: |
http , server , location
|
Sets the number
and size
of the
buffers used for reading a response from a disk.
Prior to version 1.9.5, the default value was 1 32k.
Syntax: |
port_in_redirect
|
---|---|
Default: |
port_in_redirect on; |
Context: |
http , server , location
|
Enables or disables specifying the port in
absolute redirects issued by nginx.
The use of the primary server name in redirects is controlled by
the server_name_in_redirect directive.
Syntax: |
postpone_output
|
---|---|
Default: |
postpone_output 1460; |
Context: |
http , server , location
|
If possible, the transmission of client data will be postponed until
nginx has at least size
bytes of data to send.
The zero value disables postponing data transmission.
Syntax: |
read_ahead
|
---|---|
Default: |
read_ahead 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_SEQUENTIAL)
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.
Syntax: |
recursive_error_pages
|
---|---|
Default: |
recursive_error_pages off; |
Context: |
http , server , location
|
Enables or disables doing several redirects using the
error_page
directive.
The number of such redirects is limited.
Syntax: |
request_pool_size
|
---|---|
Default: |
request_pool_size 4k; |
Context: |
http , server
|
Allows accurate tuning of per-request memory allocations.
This directive has minimal impact on performance
and should not generally be used.
Syntax: |
reset_timedout_connection
|
---|---|
Default: |
reset_timedout_connection off; |
Context: |
http , server , location
|
Enables or disables resetting timed out connections
and connections
closed
with the non-standard code 444 (1.15.2).
The reset is performed as follows.
Before closing a socket, the
SO_LINGER
option is set on it with a timeout value of 0.
When the socket is closed, TCP RST is sent to the client, and all memory
occupied by this socket is released.
This helps avoid keeping an already closed socket with filled buffers
in a FIN_WAIT1 state for a long time.
It should be noted that timed out keep-alive connections are
closed normally.
Syntax: |
resolver
|
---|---|
Default: |
— |
Context: |
http , server , location
|
Configures name servers used to resolve names of upstream servers
into addresses, for example:
resolver 127.0.0.1 [::1]:5353;
The address can be specified as a domain name or IP address,
with an optional port (1.3.1, 1.2.2).
If port is not specified, the port 53 is used.
Name servers are queried in a round-robin fashion.
Before version 1.1.7, only a single name server could be configured.
Specifying name servers using IPv6 addresses is supported
starting from versions 1.3.1 and 1.2.2.
By default, nginx will look up both IPv4 and IPv6 addresses while resolving.
If looking up of IPv4 or IPv6 addresses is not desired,
the ipv4=off
(1.23.1) or
the ipv6=off
parameter can be specified.
Resolving of names into IPv6 addresses is supported
starting from version 1.5.8.
By default, nginx caches answers using the TTL value of a response.
An optional valid
parameter allows overriding it:
resolver 127.0.0.1 [::1]:5353 valid=30s;
Before version 1.1.9, tuning of caching time was not possible,
and nginx always cached answers for the duration of 5 minutes.
To prevent DNS spoofing, it is recommended
configuring DNS servers in a properly secured trusted local network.
The optional status_zone
parameter (1.17.1)
enables
collection
of DNS server statistics of requests and responses
in the specified zone
.
The parameter is available as part of our
commercial subscription.
Syntax: |
resolver_timeout
|
---|---|
Default: |
resolver_timeout 30s; |
Context: |
http , server , location
|
Sets a timeout for name resolution, for example:
resolver_timeout 5s;
Syntax: |
root
|
---|---|
Default: |
root html; |
Context: |
http , server , location , if in location
|
Sets the root directory for requests.
For example, with the following configuration
location /i/ { root /data/w3; }
The /data/w3/i/top.gif
file will be sent in response to
the “/i/top.gif
” request.
The path
value can contain variables,
except $document_root
and $realpath_root
.
A path to the file is constructed by merely adding a URI to the value
of the root
directive.
If a URI has to be modified, the
alias directive should be used.
Syntax: |
satisfy
|
---|---|
Default: |
satisfy 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; auth_basic "closed site"; auth_basic_user_file conf/htpasswd; }
Syntax: |
send_lowat
|
---|---|
Default: |
send_lowat 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.
Syntax: |
send_timeout
|
---|---|
Default: |
send_timeout 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.
Syntax: |
sendfile
|
---|---|
Default: |
sendfile off; |
Context: |
http , server , location , if in location
|
Enables or disables the use of
sendfile()
.
Starting from nginx 0.8.12 and FreeBSD 5.2.1,
aio can be used to pre-load data
for sendfile()
:
location /video/ { sendfile on; tcp_nopush on; aio on; }
In this configuration, sendfile()
is called with
the SF_NODISKIO
flag which causes it not to block on disk I/O,
but, instead, report back that the data are not in memory.
nginx then initiates an asynchronous data load by reading one byte.
On the first read, the FreeBSD kernel loads the first 128K bytes
of a file into memory, although next reads will only load data in 16K chunks.
This can be changed using the
read_ahead directive.
Before version 1.7.11, pre-loading could be enabled with
aio sendfile;
.
Syntax: |
sendfile_max_chunk
|
---|---|
Default: |
sendfile_max_chunk 2m; |
Context: |
http , server , location
|
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.
Prior to version 1.21.4, by default there was no limit.
Syntax: |
server { ... }
|
---|---|
Default: |
— |
Context: |
http
|
Sets configuration for a virtual server.
There is no clear separation between IP-based (based on the IP address)
and name-based (based on the “Host” request header field)
virtual servers.
Instead, the listen directives describe all
addresses and ports that should accept connections for the server, and the
server_name directive lists all server names.
Example configurations are provided in the
“How nginx processes a request” document.
Syntax: |
server_name
|
---|---|
Default: |
server_name ""; |
Context: |
server
|
Sets names of a virtual server, for example:
server { server_name example.com www.example.com; }
The first name becomes the primary server name.
Server names can include an asterisk (“*
”)
replacing the first or last part of a name:
server { server_name example.com *.example.com www.example.*; }
Such names are called wildcard names.
The first two of the names mentioned above can be combined in one:
server { server_name .example.com; }
It is also possible to use regular expressions in server names,
preceding the name with a tilde (“~
”):
server { server_name www.example.com ~^wwwd+.example.com$; }
Regular expressions can contain captures (0.7.40) that can later
be used in other directives:
server { server_name ~^(www.)?(.+)$; location / { root /sites/$2; } } server { server_name _; location / { root /sites/default; } }
Named captures in regular expressions create variables (0.8.25)
that can later be used in other directives:
server { server_name ~^(www.)?(?<domain>.+)$; location / { root /sites/$domain; } } server { server_name _; location / { root /sites/default; } }
If the directive’s parameter is set to “$hostname
” (0.9.4), the
machine’s hostname is inserted.
It is also possible to specify an empty server name (0.7.11):
server { server_name www.example.com ""; }
It allows this server to process requests without the “Host”
header field — instead of the default server — for the given address:port pair.
This is the default setting.
Before 0.8.48, the machine’s hostname was used by default.
During searching for a virtual server by name,
if the name matches more than one of the specified variants,
(e.g. both a wildcard name and regular expression match), the first matching
variant will be chosen, in the following order of priority:
- the exact name
-
the longest wildcard name starting with an asterisk,
e.g. “*.example.com
” -
the longest wildcard name ending with an asterisk,
e.g. “mail.*
” -
the first matching regular expression
(in order of appearance in the configuration file)
Detailed description of server names is provided in a separate
Server names document.
Syntax: |
server_name_in_redirect
|
---|---|
Default: |
server_name_in_redirect off; |
Context: |
http , server , location
|
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.
Syntax: |
server_names_hash_bucket_size
|
---|---|
Default: |
server_names_hash_bucket_size 32|64|128; |
Context: |
http
|
Sets the bucket size for the server names hash tables.
The default value depends on the size of the processor’s cache line.
The details of setting up hash tables are provided in a separate
document.
Syntax: |
server_names_hash_max_size
|
---|---|
Default: |
server_names_hash_max_size 512; |
Context: |
http
|
Sets the maximum size
of the server names hash tables.
The details of setting up hash tables are provided in a separate
document.
Syntax: |
server_tokens
|
---|---|
Default: |
server_tokens on; |
Context: |
http , server , location
|
Enables or disables emitting nginx version on error pages and in the
“Server” response header field.
The build
parameter (1.11.10) enables emitting
a build name
along with nginx version.
Additionally, as part of our
commercial subscription,
starting from version 1.9.13
the signature on error pages and
the “Server” response header field value
can be set explicitly using the string
with variables.
An empty string disables the emission of the “Server” field.
Syntax: |
subrequest_output_buffer_size
|
---|---|
Default: |
subrequest_output_buffer_size 4k|8k; |
Context: |
http , server , location
|
This directive appeared in version 1.13.10.
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.
Syntax: |
tcp_nodelay
|
---|---|
Default: |
tcp_nodelay on; |
Context: |
http , server , location
|
Enables or disables the use of the TCP_NODELAY
option.
The option is enabled when a connection is transitioned into the
keep-alive state.
Additionally, it is enabled on SSL connections,
for unbuffered proxying,
and for WebSocket proxying.
Syntax: |
tcp_nopush
|
---|---|
Default: |
tcp_nopush off; |
Context: |
http , server , location
|
Enables or disables the use of
the TCP_NOPUSH
socket option on FreeBSD
or the TCP_CORK
socket option on Linux.
The options are enabled only when sendfile is used.
Enabling the option allows
-
sending the response header and the beginning of a file in one packet,
on Linux and FreeBSD 4.*; - sending a file in full packets.
Syntax: |
try_files try_files
|
---|---|
Default: |
— |
Context: |
server , location
|
Checks the existence of files in the specified order and uses
the first found file for request processing; the processing
is performed in the current context.
The path to a file is constructed from the
file
parameter
according to the
root and alias directives.
It is possible to check directory’s existence by specifying
a slash at the end of a name, e.g. “$uri/
”.
If none of the files were found, an internal redirect to the
uri
specified in the last parameter is made.
For example:
location /images/ { try_files $uri /images/default.gif; } location = /images/default.gif { expires 30s; }
The last parameter can also point to a named location,
as shown in examples below.
Starting from version 0.7.51, the last parameter can also be a
code
:
location / { try_files $uri $uri/index.html $uri.html =404; }
Example in proxying Mongrel:
location / { try_files /system/maintenance.html $uri $uri/index.html $uri.html @mongrel; } location @mongrel { proxy_pass http://mongrel; }
Example for Drupal/FastCGI:
location / { try_files $uri $uri/ @drupal; } location ~ .php$ { try_files $uri @drupal; fastcgi_pass ...; fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param QUERY_STRING $args; ... other fastcgi_param's } location @drupal { fastcgi_pass ...; fastcgi_param SCRIPT_FILENAME /path/to/index.php; fastcgi_param SCRIPT_NAME /index.php; fastcgi_param QUERY_STRING q=$uri&$args; ... other fastcgi_param's }
In the following example,
location / { try_files $uri $uri/ @drupal; }
the try_files
directive is equivalent to
location / { error_page 404 = @drupal; log_not_found off; }
And here,
location ~ .php$ { try_files $uri @drupal; fastcgi_pass ...; fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name; ... }
try_files
checks the existence of the PHP file
before passing the request to the FastCGI server.
Example for WordPress and Joomla:
location / { try_files $uri $uri/ @wordpress; } location ~ .php$ { try_files $uri @wordpress; fastcgi_pass ...; fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name; ... other fastcgi_param's } location @wordpress { fastcgi_pass ...; fastcgi_param SCRIPT_FILENAME /path/to/index.php; ... other fastcgi_param's }
Syntax: |
types { ... }
|
---|---|
Default: |
types { text/html html; image/gif gif; image/jpeg jpg; } |
Context: |
http , server , location
|
Maps file name extensions to MIME types of responses.
Extensions are case-insensitive.
Several extensions can be mapped to one type, for example:
types { application/octet-stream bin exe dll; application/octet-stream deb; application/octet-stream dmg; }
A sufficiently full mapping table is distributed with nginx in the
conf/mime.types
file.
To make a particular location emit the
“application/octet-stream
”
MIME type for all requests, the following configuration can be used:
location /download/ { types { } default_type application/octet-stream; }
Syntax: |
types_hash_bucket_size
|
---|---|
Default: |
types_hash_bucket_size 64; |
Context: |
http , server , location
|
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.
Syntax: |
types_hash_max_size
|
---|---|
Default: |
types_hash_max_size 1024; |
Context: |
http , server , location
|
Sets the maximum size
of the types hash tables.
The details of setting up hash tables are provided in a separate
document.
Syntax: |
underscores_in_headers
|
---|---|
Default: |
underscores_in_headers off; |
Context: |
http , server
|
Enables or disables the use of underscores in client request header fields.
When the use of underscores is disabled, request header fields whose names
contain underscores are
marked as invalid and become subject to the
ignore_invalid_headers directive.
If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.
Syntax: |
variables_hash_bucket_size
|
---|---|
Default: |
variables_hash_bucket_size 64; |
Context: |
http
|
Sets the bucket size for the variables hash table.
The details of setting up hash tables are provided in a separate
document.
Syntax: |
variables_hash_max_size
|
---|---|
Default: |
variables_hash_max_size 1024; |
Context: |
http
|
Sets the maximum size
of the variables hash table.
The details of setting up hash tables are provided in a separate
document.
Prior to version 1.5.13, the default value was 512.
Embedded Variables
The ngx_http_core_module
module supports embedded variables
with names matching the Apache Server variables.
First of all, these are variables representing client request header
fields, such as $http_user_agent
, $http_cookie
,
and so on.
Also there are other variables:
$arg_
name
-
argument
name
in the request line $args
- arguments in the request line
$binary_remote_addr
-
client address in a binary form, value’s length is always 4 bytes
for IPv4 addresses or 16 bytes for IPv6 addresses $body_bytes_sent
-
number of bytes sent to a client, not counting the response header;
this variable is compatible with the “%B
” parameter of the
mod_log_config
Apache module $bytes_sent
- number of bytes sent to a client (1.3.8, 1.2.5)
$connection
- connection serial number (1.3.8, 1.2.5)
$connection_requests
- current number of requests made through a connection (1.3.8, 1.2.5)
$connection_time
- connection time in seconds with a milliseconds resolution (1.19.10)
$content_length
- “Content-Length” request header field
$content_type
- “Content-Type” request header field
$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 (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 (1.11.0)
The PROXY protocol must be previously enabled by setting the
proxy_protocol
parameter
in the listen directive. $proxy_protocol_server_addr
-
server address from the PROXY protocol header (1.17.6)
The PROXY protocol must be previously enabled by setting the
proxy_protocol
parameter
in the listen directive. $proxy_protocol_server_port
-
server port from the PROXY protocol header (1.17.6)
The PROXY protocol must be previously enabled by setting the
proxy_protocol
parameter
in the listen directive. $proxy_protocol_tlv_
name
-
TLV from the PROXY Protocol header (1.23.2).
Thename
can be a TLV type name or its numeric value.
In the latter case, the value is hexadecimal
and should be prefixed with0x
:$proxy_protocol_tlv_alpn $proxy_protocol_tlv_0x01
SSL TLVs can also be accessed by TLV type name
or its numeric value,
both prefixed byssl_
:$proxy_protocol_tlv_ssl_version $proxy_protocol_tlv_ssl_0x21
The following TLV type names are supported:
-
alpn
(0x01
) —
upper layer protocol used over the connection -
authority
(0x02
) —
host name value passed by the client -
unique_id
(0x05
) —
unique connection id -
netns
(0x30
) —
name of the namespace -
ssl
(0x20
) —
binary SSL TLV structure
The following SSL TLV type names are supported:
-
ssl_version
(0x21
) —
SSL version used in client connection -
ssl_cn
(0x22
) —
SSL certificate Common Name -
ssl_cipher
(0x23
) —
name of the used cipher -
ssl_sig_alg
(0x24
) —
algorithm used to sign the certificate -
ssl_key_alg
(0x25
) —
public-key algorithm
Also, the following special SSL TLV type name is supported:
-
ssl_verify
—
client SSL certificate verification result,
0
if the client presented a certificate
and it was successfully verified,
non-zero otherwise.
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 theproxy_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 thebind
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 theTCP_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.
Configure NGINX and NGINX Plus as a web server, with support for virtual server multi-tenancy, URI and response rewriting, variables, and error handling.
This article explains how to configure NGINX Open Source and NGINX Plus as a web server, and includes the following sections:
- Setting Up Virtual Servers
- Configuring Locations
- Location Priority
- Using Variables
- Returning Specific Status Codes
- Rewriting URIs in Requests
- Rewriting HTTP Responses
- Handling Errors
For additional information on how to tune NGINX Plus and NGINX Open Source, watch our free webinar on-demand Installing and Tuning NGINX.
Note: The information in this article applies to both NGINX Open Source and NGINX Plus. For ease of reading, the remainder of the article refers to NGINX Plus only.
At a high level, configuring NGINX Plus as a web server is a matter of defining which URLs it handles and how it processes HTTP requests for resources at those URLs. At a lower level, the configuration defines a set of virtual servers that control the processing of requests for particular domains or IP addresses. For more information about configuration files, see Creating NGINX Plus Configuration Files.
Each virtual server for HTTP traffic defines special configuration instances called locations that control processing of specific sets of URIs. Each location defines its own scenario of what happens to requests that are mapped to this location. NGINX Plus provides full control over this process. Each location can proxy the request or return a file. In addition, the URI can be modified, so that the request is redirected to another location or virtual server. Also, a specific error code can be returned and you can configure a specific page to correspond to each error code.
Setting Up Virtual Servers
The NGINX Plus configuration file must include at least one server directive to define a virtual server. When NGINX Plus processes a request, it first selects the virtual server that will serve the request.
A virtual server is defined by a server
directive in the http
context, for example:
http {
server {
# Server configuration
}
}
It is possible to add multiple server
directives into the http
context to define multiple virtual servers.
The server
configuration block usually includes a listen directive to specify the IP address and port (or Unix domain socket and path) on which the server listens for requests. Both IPv4 and IPv6 addresses are accepted; enclose IPv6 addresses in square brackets.
The example below shows configuration of a server that listens on IP address 127.0.0.1 and port 8080:
server {
listen 127.0.0.1:8080;
# Additional server configuration
}
If a port is omitted, the standard port is used. Likewise, if an address is omitted, the server listens on all addresses. If the listen
directive is not included at all, the “standard” port is 80/tcp
and the “default” port is 8000/tcp
, depending on superuser privileges.
If there are several servers that match the IP address and port of the request, NGINX Plus tests the request’s Host
header field against the server_name directives in the server
blocks. The parameter to server_name
can be a full (exact) name, a wildcard, or a regular expression. A wildcard is a character string that includes the asterisk (*
) at its beginning, end, or both; the asterisk matches any sequence of characters. NGINX Plus uses the Perl syntax for regular expressions; precede them with the tilde (~
). This example illustrates an exact name.
server {
listen 80;
server_name example.org www.example.org;
#...
}
If several names match the Host
header, NGINX Plus selects one by searching for names in the following order and using the first match it finds:
- Exact name
- Longest wildcard starting with an asterisk, such as
*.example.org
- Longest wildcard ending with an asterisk, such as
mail.*
- First matching regular expression (in order of appearance in the configuration file)
If the Host
header field does not match a server name, NGINX Plus routes the request to the default server for the port on which the request arrived. The default server is the first one listed in the nginx.conf file, unless you include the default_server
parameter to the listen
directive to explicitly designate a server as the default.
server {
listen 80 default_server;
#...
}
Configuring Locations
NGINX Plus can send traffic to different proxies or serve different files based on the request URIs. These blocks are defined using the location directive placed within a server
directive.
For example, you can define three location
blocks to instruct the virtual server to send some requests to one proxied server, send other requests to a different proxied server, and serve the rest of the requests by delivering files from the local file system.
NGINX Plus tests request URIs against the parameters of all location
directives and applies the directives defined in the matching location. Inside each location
block, it is usually possible (with a few exceptions) to place even more location
directives to further refine the processing for specific groups of requests.
Note: In this guide, the word location refers to a single location context.
There are two types of parameter to the location
directive: prefix strings (pathnames) and regular expressions. For a request URI to match a prefix string, it must start with the prefix string.
The following sample location with a pathname parameter matches request URIs that begin with /some/path/, such as /some/path/document.html. (It does not match /my-site/some/path because /some/path does not occur at the start of that URI.)
location /some/path/ {
#...
}
A regular expression is preceded with the tilde (~
) for case-sensitive matching, or the tilde-asterisk (~*
) for case-insensitive matching. The following example matches URIs that include the string .html or .htm in any position.
location ~ .html? {
#...
}
NGINX Location Priority
To find the location that best matches a URI, NGINX Plus first compares the URI to the locations with a prefix string. It then searches the locations with a regular expression.
Higher priority is given to regular expressions, unless the ^~
modifier is used. Among the prefix strings NGINX Plus selects the most specific one (that is, the longest and most complete string). The exact logic for selecting a location to process a request is given below:
- Test the URI against all prefix strings.
- The
=
(equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops. - If the
^~
(caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked. - Store the longest matching prefix string.
- Test the URI against regular expressions.
- Stop processing when the first matching regular expression is found and use the corresponding location.
- If no regular expression matches, use the location corresponding to the stored prefix string.
A typical use case for the =
modifier is requests for / (forward slash). If requests for / are frequent, specifying = /
as the parameter to the location
directive speeds up processing, because the search for matches stops after the first comparison.
A location
context can contain directives that define how to resolve a request – either serve a static file or pass the request to a proxied server. In the following example, requests that match the first location
context are served files from the /data directory and the requests that match the second are passed to the proxied server that hosts content for the www.example.com domain.
server {
location /images/ {
root /data;
}
location / {
proxy_pass http://www.example.com;
}
}
The root directive specifies the file system path in which to search for the static files to serve. The request URI associated with the location is appended to the path to obtain the full name of the static file to serve. In the example above, in response to a request for /images/example.png, NGINX Plus delivers the file /data/images/example.png.
The proxy_pass directive passes the request to the proxied server accessed with the configured URL. The response from the proxied server is then passed back to the client. In the example above, all requests with URIs that do not start with /images/ are be passed to the proxied server.
Using Variables
You can use variables in the configuration file to have NGINX Plus process requests differently depending on defined circumstances. Variables are named values that are calculated at runtime and are used as parameters to directives. A variable is denoted by the $
(dollar) sign at the beginning of its name. Variables define information based upon NGINX’s state, such as the properties of the request being currently processed.
There are a number of predefined variables, such as the core HTTP variables, and you can define custom variables using the set, map, and geo directives. Most variables are computed at runtime and contain information related to a specific request. For example, $remote_addr
contains the client IP address and $uri
holds the current URI value.
Returning Specific Status Codes
Some website URIs require immediate return of a response with a specific error or redirect code, for example when a page has been moved temporarily or permanently. The easiest way to do this is to use the return directive. For example:
location /wrong/url {
return 404;
}
The first parameter of return
is a response code. The optional second parameter can be the URL of a redirect (for codes 301
, 302
, 303
, and 307
) or the text to return in the response body. For example:
location /permanently/moved/url {
return 301 http://www.example.com/moved/here;
}
The return
directive can be included in both the location
and server
contexts.
Rewriting URIs in Requests
A request URI can be modified multiple times during request processing through the use of the rewrite directive, which has one optional and two required parameters. The first (required) parameter is the regular expression that the request URI must match. The second parameter is the URI to substitute for the matching URI. The optional third parameter is a flag that can halt processing of further rewrite
directives or send a redirect (code 301
or 302
). For example:
location /users/ {
rewrite ^/users/(.*)$ /show?user=$1 break;
}
As this example shows, the second parameter users
captures though matching of regular expressions.
You can include multiple rewrite
directives in both the server
and location
contexts. NGINX Plus executes the directives one-by-one in the order they occur. The rewrite
directives in a server
context are executed once when that context is selected.
After NGINX processes a set of rewriting instructions, it selects a location
context according to the new URI. If the selected location contains rewrite
directives, they are executed in turn. If the URI matches any of those, a search for the new location starts after all defined rewrite
directives are processed.
The following example shows rewrite
directives in combination with a return
directive.
server {
#...
rewrite ^(/download/.*)/media/(w+).?.*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(w+).?.*$ $1/mp3/$2.ra last;
return 403;
#...
}
This example configuration distinguishes between two sets of URIs. URIs such as /download/some/media/file are changed to /download/some/mp3/file.mp3. Because of the last
flag, the subsequent directives (the second rewrite
and the return
directive) are skipped but NGINX Plus continues processing the request, which now has a different URI. Similarly, URIs such as /download/some/audio/file are replaced with /download/some/mp3/file.ra. If a URI doesn’t match either rewrite
directive, NGINX Plus returns the 403
error code to the client.
There are two parameters that interrupt processing of rewrite
directives:
last
– Stops execution of therewrite
directives in the currentserver
orlocation
context, but NGINX Plus searches for locations that match the rewritten URI, and anyrewrite
directives in the new location are applied (meaning the URI can be changed again).break
– Like the break directive, stops processing ofrewrite
directives in the current context and cancels the search for locations that match the new URI. Therewrite
directives in the new location are not executed.
Rewriting HTTP Responses
Sometimes you need to rewrite or change the content in an HTTP response, substituting one string for another. You can use the sub_filter directive to define the rewrite to apply. The directive supports variables and chains of substitutions, making more complex changes possible.
For example, you can change absolute links that refer to a server other than the proxy:
location / {
sub_filter /blog/ /blog-staging/;
sub_filter_once off;
}
Another example changes the scheme from http://
to https://
and replaces the localhost
address with the hostname from the request header field. The sub_filter_once directive tells NGINX to apply sub_filter directives consecutively within a location:
location / {
sub_filter 'href="http://127.0.0.1:8080/' 'href="https://$host/';
sub_filter 'img src="http://127.0.0.1:8080/' 'img src="https://$host/';
sub_filter_once on;
}
Note that the part of the response already modified with the sub_filter
is not replaced again if another sub_filter
match occurs.
Handling Errors
With the error_page directive, you can configure NGINX Plus to return a custom page along with an error code, substitute a different error code in the response, or redirect the browser to a different URI. In the following example, the error_page
directive specifies the page (/404.html) to return with the 404
error code.
error_page 404 /404.html;
Note that this directive does not mean that the error is returned immediately (the return
directive does that), but simply specifies how to treat errors when they occur. The error code can come from a proxied server or occur during processing by NGINX Plus (for example, the 404
results when NGINX Plus can’t find the file requested by the client).
In the following example, when NGINX Plus cannot find a page, it substitutes code 301
for code 404
, and redirects the client to http:/example.com/new/path.html. This configuration is useful when clients are still trying to access a page at its old URI. The 301
code informs the browser that the page has moved permanently, and it needs to replace the old address with the new one automatically upon return.
location /old/path.html {
error_page 404 =301 http:/example.com/new/path.html;
}
The following configuration is an example of passing a request to the back end when a file is not found. Because there is no status code specified after the equals sign in the error_page
directive, the response to the client has the status code returned by the proxied server (not necessarily 404
).
server {
...
location /images/ {
# Set the root directory to search for the file
root /data/www;
# Disable logging of errors related to file existence
open_file_cache_errors off;
# Make an internal redirect if the file is not found
error_page 404 = /fetch$uri;
}
location /fetch/ {
proxy_pass http://backend/;
}
}
The error_page
directive instructs NGINX Plus to make an internal redirect when a file is not found. The $uri
variable in the final parameter to the error_page
directive holds the URI of the current request, which gets passed in the redirect.
For example, if /images/some/file is not found, it is replaced with /fetch/images/some/file and a new search for a location starts. As a result, the request ends up in the second location
context and is proxied to http://backend/.
The open_file_cache_errors directive prevents writing an error message if a file is not found. This is not necessary here since missing files are correctly handled.
Im trying to display the error page in /temp/www/error403.html whenever a 403 error occurs.
This should be whenever a user tries to access the site via https (ssl) and it’s IP is in the blovkips.conf file, but at the moment it still shows nginx’s default error page.
I have the same code for my other server (without any blocking) and it works.
Is it blocking the IP from accessing the custom 403 page?
If so how do I get it to work?
server {
# ssl
listen 443;
ssl on;
ssl_certificate /etc/nginx/ssl/site.in.crt;
ssl_certificate_key /etc/nginx/ssl/site.in.key;
keepalive_timeout 70;
server_name localhost;
location / {
root /temp/www;
index index.html index.htm;
}
# redirect server error pages to the static page
error_page 403 /error403.html;
# location = /error403.html {
# root /temp/www;
# }
# add trailing slash if missing
if (-f $document_root/$host$uri) {
rewrite ^(.*[^/])$ $1/ permanent;
}
# list of IPs to block
include blockips.conf;
}
Edit:
Corrected error_page code from 504 to 403 but I still have the same issue
asked Jun 25, 2010 at 15:09
MintMint
13.9k30 gold badges73 silver badges108 bronze badges
I did heaps of googling before coming here but did some more just now, within 5 minutes I had my answer
Seems I’m not the only person to have this issue:
error_page 403 /e403.html;
location = /e403.html {
root html;
allow all;
}
http://www.cyberciti.biz/faq/unix-linux-nginx-custom-error-403-page-configuration/
Seems that I was right in thinking that access to my error page was getting blocked.
msanford
11.6k10 gold badges67 silver badges92 bronze badges
answered Jul 1, 2010 at 1:08
MintMint
13.9k30 gold badges73 silver badges108 bronze badges
0
The problem might be that you’re trying to server a 403 «Forbidden» error from a webserver that they are forbidden from accessing. Nginx treats the error_page directive as an internal redirect. So it is trying to server https://example.com/error403.html which is also forbidden.
So you need to make the error page not served out of https like this:
error_page 403 http://example.com/error403.html
or add the necessary «access allowed» options to the location for the error page path. The way to test this is to access the /error403.html page directly. If you can’t accesses that way, it isn’t going to work when someone gets an actual 403 error.
answered Jul 1, 2010 at 18:56
I had the same issue… The point is that i’ve implemented ip whitelist at server context level (or vhost level if you prefer), so every locations will have this as well (basicaly /403.html won’t be accessible) :
server {
listen *:443 ssl;
server_name mydomain.com ;
error_page 403 /403.html;
.....
if ($exclusion = 0) { return 403; } #implemented in another conf.d files (see below)
location ~ .php$ {
root /var/www/vhosts/mydomain.com/httpdocs;
include /etc/nginx/fastcgi_par
fastcgi_pass 127.0.0.1:9000;
fastcgi_connect_timeout 3m;
fastcgi_read_timeout 3m;
fastcgi_send_timeout 3m;
}
location /403.html {
root /usr/share/nginx/html;
allow all;
}
...
}
Exclusion conf.d file sample:
geo $exclusion {
default 0;
10.0.0.0/8 Local network
80.23.120.23 Some_ip
...
}
To fix that simply do your return 403 at location level (context):
server {
listen *:443 ssl;
server_name mydomain.com ;
error_page 403 /403.html;
.....
location ~ .php$ {
if ($exclusion = 0) { return 403; }
root /var/www/vhosts/mydomain.com/httpdocs;
include /etc/nginx/fastcgi_par
fastcgi_pass 127.0.0.1:9000;
fastcgi_connect_timeout 3m;
fastcgi_read_timeout 3m;
fastcgi_send_timeout 3m;
}
location /403.html {
root /usr/share/nginx/html;
allow all;
}
...
}
Works for me.
answered Jul 22, 2016 at 13:41
It looks like there’s a boo-boo in the listed configuration, as it is only sending error code 503 («service unavailable») to the custom page, so for 403 («forbidden») you probably want to use:
error_page 403 /error403.html
Dave Jarvis
29.9k39 gold badges177 silver badges310 bronze badges
answered Jun 30, 2010 at 19:26
ewallewall
26.6k15 gold badges68 silver badges84 bronze badges
4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
error_page 500 /500.html; | |
location /500.html{ | |
return 500 ‘{«error»: {«status_code»: 500,»status»: «Internal Server Error»}}’; | |
} | |
error_page 502 /502.html; | |
location /502.html{ | |
return 502 ‘{«error»: {«status_code»: 502,»status»: «Bad Gateway»}}’; | |
} | |
error_page 503 /503.html; | |
location /503.html{ | |
return 503 ‘{«error»: {«status_code»: 503,»status»: «Service Temporarily Unavailable»}}’; | |
} | |
error_page 504 /504.html; | |
location /504.html{ | |
return 504 ‘{«error»: {«status_code»: 504,»status»: «Gateway Timeout»}}’; | |
} | |
error_page 400 /400.html; | |
location /400.html{ | |
return 400 ‘{«error»: {«status_code»: 400,»status»: «Bad Request»}}’; | |
} | |
error_page 401 /401.html; | |
location /401.html{ | |
return 401 ‘{«error»: {«status_code»: 401,»status»: «Unauthorized»}}’; | |
} | |
error_page 403 /403.html; | |
location /403.html{ | |
return 403 ‘{«error»: {«status_code»: 403,»status»: «Forbidden»}}’; | |
} | |
error_page 404 /404.html; | |
location /404.html{ | |
return 404 ‘{«error»: {«status_code»: 404,»status»: «Not Found»}}’; | |
} | |
error_page 408 /408.html; | |
location /408.html{ | |
return 408 ‘{«error»: {«status_code»: 408,»status»: «Request Timeout}}’; | |
} | |
error_page 418 /418.html; | |
location /418.html{ | |
return 418 ‘{«error»: {«status_code»: 418,»status»: «I‘m a teapot»}}’; | |
} | |
При разработке API часто бывает так, что абсолютно все ответы даже с непредвиденными ошибками нужно отдавать в json-формате. В плане PHP, ошибки и эксепшены перехватывать достаточно легко. А вот 500, 502, 504, 404 и прочие ошибки могут генерироваться уже не на стороне PHP, а на стороне веб-сервера, например, nginx. В таком случае нужно править конфигурацию веб-сервера. Можно создать отдельный файл errors.conf:
error_page 500 =200 /500.json;
location /500.json {
return 500 '{"error": {"status_code": 500,"status": "Internal Server Error"}}';
}
error_page 502 =200 /502.json;
location /502.json {
return 502 '{"error": {"status_code": 502,"status": "Bad Gateway"}}';
}
error_page 503 =200 /503.json;
location /503.json {
return 503 '{"error": {"status_code": 503,"status": "Service Temporarily Unavailable"}}';
}
error_page 504 =200 /504.json;
location /504.json {
return 504 '{"error": {"status_code": 504,"status": "Gateway Timeout"}}';
}
error_page 400 =200 /400.json;
location /400.json {
return 400 '{"error": {"status_code": 400,"status": "Bad Request"}}';
}
error_page 401 =200 /401.json;
location /401.json {
return 401 '{"error": {"status_code": 401,"status": "Unauthorized"}}';
}
error_page 403 =200 /403.json;
location /403.json {
return 403 '{"error": {"status_code": 403,"status": "Forbidden"}}';
}
error_page 404 =200 /404.json;
location /404.json {
return 404 '{"error": {"status_code": 404,"status": "Not Found"}}';
}
error_page 408 =200 /408.json;
location /408.json {
return 408 '{"error": {"status_code": 408,"status": "Request Timeout}}';
}
error_page 418 =200 /418.json;
location /418.json {
return 418 '{"error": {"status_code": 418,"status": "I'm a teapot"}}';
}
А затем в добавить в конфигурацию нужного домена строку:
include errors.conf;
Можете кстати попробовать добавить это в контексте всех http серверов, судя по документации это не запрещено.
Кратко как это работает. Директива error_page имеет такой синтаксис:
error_page код ... [=[ответ]] uri;
Т.е. для указанного кода ответа можно переопределить сам код ответа, например, возвращать всегда код 200, а код ошибки сообщать уже в json-ответе. Также нужно указать uri с содержимым ответа. Это может быть как файл на диске, так и внутренний локейшен. Чем, собственно, и воспользуемся.
В объявлении локейшена нет ничего необычного, поэтому сразу рассмотрим его содержимое. Директива return может быть описана тремя способами:
return код [текст];
return код URL;
return URL;
В данном случае нас интересует только первый вариант. При указании любого кода, за исключением кодов 301, 302, 303, 307 и 308 можно задать тела ответа, которое будет отправлено клиенту. Также в тексте тела ответа можно использовать переменные.
Ещё один способ отдавать ошибки nginx в json-формате
Можно воспользоваться другим вариантом и хранить тексты ответов в отдельных файлах.
error_page 511 /errors/511.json;
error_page 507 /errors/507.json;
error_page 506 /errors/506.json;
error_page 451 /errors/451.json;
error_page 431 /errors/431.json;
error_page 429 /errors/429.json;
error_page 428 /errors/428.json;
error_page 424 /errors/424.json;
error_page 423 /errors/423.json;
error_page 422 /errors/422.json;
error_page 505 /errors/505.json;
error_page 504 /errors/504.json;
error_page 503 /errors/503.json;
error_page 502 /errors/502.json;
error_page 501 /errors/501.json;
error_page 500 /errors/500.json;
error_page 426 /errors/426.json;
error_page 417 /errors/417.json;
error_page 416 /errors/416.json;
error_page 415 /errors/415.json;
error_page 414 /errors/414.json;
error_page 413 /errors/413.json;
error_page 412 /errors/412.json;
error_page 411 /errors/411.json;
error_page 410 /errors/410.json;
error_page 409 /errors/409.json;
error_page 408 /errors/408.json;
error_page 407 /errors/407.json;
error_page 406 /errors/406.json;
error_page 405 /errors/405.json;
error_page 404 /errors/404.json;
error_page 403 /errors/403.json;
error_page 402 /errors/402.json;
error_page 401 /errors/401.json;
error_page 400 /errors/400.json;
location ^~ /errors/ {
internal;
root <PATH TO PARENT FOLDER OF ERRORS FOLDER>;
}
Post Views:
2 754
Содержание
- Module ngx_http_api_module
- Example Configuration
- Directives
- Compatibility
- Endpoints
- Response Objects
Module ngx_http_api_module
Directives
api
status_zone
Compatibility
Endpoints
/
/nginx
/processes
/connections
/slabs/
/slabs/
/http/
/http/requests
/http/server_zones/
/http/server_zones/
/http/location_zones/
/http/location_zones/
/http/caches/
/http/caches/
/http/limit_conns/
/http/limit_conns/
/http/limit_reqs/
/http/limit_reqs/
/http/upstreams/
/http/upstreams//
/http/upstreams//servers/
/http/upstreams//servers/
/http/keyvals/
/http/keyvals/
/stream/
/stream/server_zones/
/stream/server_zones/
/stream/limit_conns/
/stream/limit_conns/
/stream/upstreams/
/stream/upstreams//
/stream/upstreams//servers/
/stream/upstreams//servers/
/stream/keyvals/
/stream/keyvals/
/stream/zone_sync/
/resolvers/
/resolvers/
/ssl
Response Objects
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.
When using the PATCH or POST methods, make sure that the payload does not exceed the buffer size for reading the client request body, otherwise, the 413 (Request Entity Too Large) error may be returned.
Example Configuration
All API requests include a supported API version in the URI. Examples of API requests with this configuration:
Directives
Syntax: | api [ write = on | off ]; |
---|---|
Default: | — |
Context: | location |
Turns on the REST API interface in the surrounding location. Access to this location should be limited.
The write parameter determines whether the API is read-only or read-write. By default, the API is read-only.
All API requests should contain a supported API version in the URI. If the request URI equals the location prefix, the list of supported API versions is returned. The current API version is “ 8 ”.
The optional “ fields ” argument in the request line specifies which fields of the requested objects will be output:
Syntax: | status_zone zone ; |
---|---|
Default: | — |
Context: | server , location , if in location |
This directive appeared in version 1.13.12.
Enables collection of virtual http or stream server status information in the specified zone . Several servers may share the same zone.
Starting from 1.17.0, status information can be collected per location. The special value off disables statistics collection in nested location blocks. Note that the statistics is collected 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.
Compatibility
- The ssl data for each HTTP upstream, server zone, and stream upstream, server zone, were added in version 8.
- The codes data in responses for each HTTP upstream, server zone, and location zone were added in version 7.
- The /stream/limit_conns/ data were added in version 6.
- The /http/limit_conns/ data were added in version 6.
- The /http/limit_reqs/ data were added in version 6.
- The “ expire ” parameter of a key-value pair can be set or changed since version 5.
- The /resolvers/ data were added in version 5.
- The /http/location_zones/ data were added in version 5.
- The path and method fields of nginx error object were removed in version 4. These fields continue to exist in earlier api versions, but show an empty value.
- The /stream/zone_sync/ data were added in version 3.
- The drain parameter was added in version 2.
- The /stream/keyvals/ data were added in version 2.
Endpoints
- GET — Return list of root endpoints
Returns a list of root endpoints.
- 200 — Success, returns an array of strings
- 404 — Unknown version ( UnknownVersion ), returns Error
/nginx
- GET — Return status of nginx running instance
Returns nginx version, build name, address, number of configuration reloads, IDs of master and worker processes.
fields ( string , optional) Limits which fields of nginx running instance will be output.
- 200 — Success, returns nginx
- 404 — Unknown version ( UnknownVersion ), returns Error
/processes
- GET — Return nginx processes status
Returns the number of abnormally terminated and respawned child processes.
- 200 — Success, returns Processes
- 404 — Unknown version ( UnknownVersion ), returns Error
Resets counters of abnormally terminated and respawned child processes.
- 204 — Success
- 404 — Unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/connections
- GET — Return client connections statistics
Returns statistics of client connections.
fields ( string , optional) Limits which fields of the connections statistics will be output.
- 200 — Success, returns Connections
- 404 — Unknown version ( UnknownVersion ), returns Error
Resets statistics of accepted and dropped client connections.
- 204 — Success
- 404 — Unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/slabs/
- GET — Return status of all slabs
Returns status of slabs for each shared memory zone with slab allocator.
fields ( string , optional) Limits which fields of slab zones will be output. If the “ fields ” value is empty, then only zone names will be output.
- 200 — Success, returns a collection of «Shared memory zone with slab allocator» objects for all slabs
- 404 — Unknown version ( UnknownVersion ), returns Error
/slabs/ Parameters common for all methods: slabZoneName ( string , required) The name of the shared memory zone with slab allocator.
- GET — Return status of a slab
Returns status of slabs for a particular shared memory zone with slab allocator.
fields ( string , optional) Limits which fields of the slab zone will be output.
- 200 — Success, returns Shared memory zone with slab allocator
- 404 — Slab not found ( SlabNotFound ), unknown version ( UnknownVersion ), returns Error
Resets the “ reqs ” and “ fails ” metrics for each memory slot.
- 204 — Success
- 404 — Slab not found ( SlabNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/
- GET — Return list of HTTP-related endpoints
Returns a list of first level HTTP endpoints.
- 200 — Success, returns an array of strings
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/requests
- GET — Return HTTP requests statistics
Returns status of client HTTP requests.
fields ( string , optional) Limits which fields of client HTTP requests statistics will be output.
- 200 — Success, returns HTTP Requests
- 404 — Unknown version ( UnknownVersion ), returns Error
Resets the number of total client HTTP requests.
- 204 — Success
- 404 — Unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/server_zones/
- GET — Return status of all HTTP server zones
Returns status information for each HTTP server zone.
fields ( string , optional) Limits which fields of server zones will be output. If the “ fields ” value is empty, then only server zone names will be output.
- 200 — Success, returns a collection of «HTTP Server Zone» objects for all HTTP server zones
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/server_zones/ Parameters common for all methods: httpServerZoneName ( string , required) The name of an HTTP server zone.
- GET — Return status of an HTTP server zone
Returns status of a particular HTTP server zone.
fields ( string , optional) Limits which fields of the server zone will be output.
- 200 — Success, returns HTTP Server Zone
- 404 — Server zone not found ( ServerZoneNotFound ), unknown version ( UnknownVersion ), returns Error
Resets statistics of accepted and discarded requests, responses, received and sent bytes, counters of SSL handshakes and session reuses in a particular HTTP server zone.
- 204 — Success
- 404 — Server zone not found ( ServerZoneNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/location_zones/
- GET — Return status of all HTTP location zones
Returns status information for each HTTP location zone.
fields ( string , optional) Limits which fields of location zones will be output. If the “ fields ” value is empty, then only zone names will be output.
- 200 — Success, returns a collection of «HTTP Location Zone» objects for all HTTP location zones
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/location_zones/ Parameters common for all methods: httpLocationZoneName ( string , required) The name of an HTTP location zone.
- GET — Return status of an HTTP location zone
Returns status of a particular HTTP location zone.
fields ( string , optional) Limits which fields of the location zone will be output.
- 200 — Success, returns HTTP Location Zone
- 404 — Location zone not found ( LocationZoneNotFound ), unknown version ( UnknownVersion ), returns Error
Resets statistics of accepted and discarded requests, responses, received and sent bytes in a particular location zone.
- 204 — Success
- 404 — Location zone not found ( LocationZoneNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/caches/
- GET — Return status of all caches
Returns status of each cache configured by proxy_cache_path and other “ *_cache_path ” directives.
fields ( string , optional) Limits which fields of cache zones will be output. If the “ fields ” value is empty, then only names of cache zones will be output.
- 200 — Success, returns a collection of «HTTP Cache» objects for all HTTP caches
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/caches/ Parameters common for all methods: httpCacheZoneName ( string , required) The name of the cache zone.
- GET — Return status of a cache
Returns status of a particular cache.
fields ( string , optional) Limits which fields of the cache zone will be output.
- 200 — Success, returns HTTP Cache
- 404 — Cache not found ( CacheNotFound ), unknown version ( UnknownVersion ), returns Error
Resets statistics of cache hits/misses in a particular cache zone.
- 204 — Success
- 404 — Cache not found ( CacheNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/limit_conns/
- GET — Return status of all HTTP limit_conn zones
Returns status information for each HTTP limit_conn zone.
fields ( string , optional) Limits which fields of limit_conn zones will be output. If the “ fields ” value is empty, then only zone names will be output.
- 200 — Success, returns a collection of «HTTP Connections Limiting» objects for all HTTP limit conns
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/limit_conns/ Parameters common for all methods: httpLimitConnZoneName ( string , required) The name of a limit_conn zone.
- GET — Return status of an HTTP limit_conn zone
Returns status of a particular HTTP limit_conn zone.
fields ( string , optional) Limits which fields of the limit_conn zone will be output.
- 200 — Success, returns HTTP Connections Limiting
- 404 — limit_conn not found ( LimitConnNotFound ), unknown version ( UnknownVersion ), returns Error
Resets the connection limiting statistics.
- 204 — Success
- 404 — limit_conn not found ( LimitConnNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/limit_reqs/
- GET — Return status of all HTTP limit_req zones
Returns status information for each HTTP limit_req zone.
fields ( string , optional) Limits which fields of limit_req zones will be output. If the “ fields ” value is empty, then only zone names will be output.
- 200 — Success, returns a collection of «HTTP Requests Rate Limiting» objects for all HTTP limit reqs
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/limit_reqs/ Parameters common for all methods: httpLimitReqZoneName ( string , required) The name of a limit_req zone.
- GET — Return status of an HTTP limit_req zone
Returns status of a particular HTTP limit_req zone.
fields ( string , optional) Limits which fields of the limit_req zone will be output.
- 200 — Success, returns HTTP Requests Rate Limiting
- 404 — limit_req not found ( LimitReqNotFound ), unknown version ( UnknownVersion ), returns Error
Resets the requests limiting statistics.
- 204 — Success
- 404 — limit_req not found ( LimitReqNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/upstreams/
- GET — Return status of all HTTP upstream server groups
Returns status of each HTTP upstream server group and its servers.
fields ( string , optional) Limits which fields of upstream server groups will be output. If the “ fields ” value is empty, only names of upstreams will be output.
- 200 — Success, returns a collection of «HTTP Upstream» objects for all HTTP upstreams
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/upstreams// Parameters common for all methods: httpUpstreamName ( string , required) The name of an HTTP upstream server group.
- GET — Return status of an HTTP upstream server group
Returns status of a particular HTTP upstream server group and its servers.
fields ( string , optional) Limits which fields of the upstream server group will be output.
- 200 — Success, returns HTTP Upstream
- 400 — Upstream is static ( UpstreamStatic ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
Resets the statistics for each upstream server in an upstream server group and queue statistics.
- 204 — Success
- 400 — Upstream is static ( UpstreamStatic ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/upstreams//servers/ Parameters common for all methods: httpUpstreamName ( string , required) The name of an upstream server group.
- GET — Return configuration of all servers in an HTTP upstream server group
Returns configuration of each server in a particular HTTP upstream server group.
- 200 — Success, returns an array of HTTP Upstream Servers
- 400 — Upstream is static ( UpstreamStatic ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
Adds a new server to an HTTP upstream server group. Server parameters are specified in the JSON format.
postHttpUpstreamServer (HTTP Upstream Server, required) Address of a new server and other optional parameters in the JSON format. The “ ID ”, “ backup ”, and “ service ” parameters cannot be changed.
- 201 — Created, returns HTTP Upstream Server
- 400 — Upstream is static ( UpstreamStatic ), invalid “ parameter ” value ( UpstreamConfFormatError ), missing “ server ” argument ( UpstreamConfFormatError ), unknown parameter “ name ” ( UpstreamConfFormatError ), nested object or list ( UpstreamConfFormatError ), “ error ” while parsing ( UpstreamBadAddress ), service upstream “ host ” may not have port ( UpstreamBadAddress ), service upstream “ host ” requires domain name ( UpstreamBadAddress ), invalid “ weight ” ( UpstreamBadWeight ), invalid “ max_conns ” ( UpstreamBadMaxConns ), invalid “ max_fails ” ( UpstreamBadMaxFails ), invalid “ fail_timeout ” ( UpstreamBadFailTimeout ), invalid “ slow_start ” ( UpstreamBadSlowStart ), reading request body failed BodyReadError ), route is too long ( UpstreamBadRoute ), “ service ” is empty ( UpstreamBadService ), no resolver defined to resolve ( UpstreamConfNoResolver ), upstream “ name ” has no backup ( UpstreamNoBackup ), upstream “ name ” memory exhausted ( UpstreamOutOfMemory ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 409 — Entry exists ( EntryExists ), returns Error
- 415 — JSON error ( JsonError ), returns Error
/http/upstreams//servers/ Parameters common for all methods: httpUpstreamName ( string , required) The name of the upstream server group. httpUpstreamServerId ( string , required) The ID of the server.
- GET — Return configuration of a server in an HTTP upstream server group
Returns configuration of a particular server in the HTTP upstream server group.
- 200 — Success, returns HTTP Upstream Server
- 400 — Upstream is static ( UpstreamStatic ), invalid server ID ( UpstreamBadServerId ), returns Error
- 404 — Server with ID “ id ” does not exist ( UpstreamServerNotFound ), unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
Modifies settings of a particular server in an HTTP upstream server group. Server parameters are specified in the JSON format.
patchHttpUpstreamServer (HTTP Upstream Server, required) Server parameters, specified in the JSON format. The “ ID ”, “ backup ”, and “ service ” parameters cannot be changed.
- 200 — Success, returns HTTP Upstream Server
- 400 — Upstream is static ( UpstreamStatic ), invalid “ parameter ” value ( UpstreamConfFormatError ), unknown parameter “ name ” ( UpstreamConfFormatError ), nested object or list ( UpstreamConfFormatError ), “ error ” while parsing ( UpstreamBadAddress ), invalid “ server ” argument ( UpstreamBadAddress ), invalid server ID ( UpstreamBadServerId ), invalid “ weight ” ( UpstreamBadWeight ), invalid “ max_conns ” ( UpstreamBadMaxConns ), invalid “ max_fails ” ( UpstreamBadMaxFails ), invalid “ fail_timeout ” ( UpstreamBadFailTimeout ), invalid “ slow_start ” ( UpstreamBadSlowStart ), reading request body failed BodyReadError ), route is too long ( UpstreamBadRoute ), “ service ” is empty ( UpstreamBadService ), server “ ID ” address is immutable ( UpstreamServerImmutable ), server “ ID ” weight is immutable ( UpstreamServerWeightImmutable ), upstream “ name ” memory exhausted ( UpstreamOutOfMemory ), returns Error
- 404 — Server with ID “ id ” does not exist ( UpstreamServerNotFound ), unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 415 — JSON error ( JsonError ), returns Error
Removes a server from an HTTP upstream server group.
- 200 — Success, returns an array of HTTP Upstream Servers
- 400 — Upstream is static ( UpstreamStatic ), invalid server ID ( UpstreamBadServerId ), server “ id ” not removable ( UpstreamServerImmutable ), returns Error
- 404 — Server with ID “ id ” does not exist ( UpstreamServerNotFound ), unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/http/keyvals/
- GET — Return key-value pairs from all HTTP keyval zones
Returns key-value pairs for each HTTP keyval shared memory zone.
fields ( string , optional) If the “ fields ” value is empty, then only HTTP keyval zone names will be output.
- 200 — Success, returns a collection of «HTTP Keyval Shared Memory Zone» objects for all HTTP keyvals
- 404 — Unknown version ( UnknownVersion ), returns Error
/http/keyvals/ Parameters common for all methods: httpKeyvalZoneName ( string , required) The name of an HTTP keyval shared memory zone.
- GET — Return key-value pairs from an HTTP keyval zone
Returns key-value pairs stored in a particular HTTP keyval shared memory zone.
key ( string , optional) Get a particular key-value pair from the HTTP keyval zone.
- 200 — Success, returns HTTP Keyval Shared Memory Zone
- 404 — Keyval not found ( KeyvalNotFound ), keyval key not found ( KeyvalKeyNotFound ), unknown version ( UnknownVersion ), returns Error
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.
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. Expiration time in milliseconds can be specified for a key-value pair with the expire parameter which overrides the timeout parameter of the keyval_zone directive.
- 201 — Created
- 400 — Invalid JSON ( KeyvalFormatError ), invalid key format ( KeyvalFormatError ), key required ( KeyvalFormatError ), keyval timeout is not enabled ( KeyvalFormatError ), only one key can be added ( KeyvalFormatError ), reading request body failed BodyReadError ), returns Error
- 404 — Keyval not found ( KeyvalNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 409 — Entry exists ( EntryExists ), key already exists ( KeyvalKeyExists ), returns Error
- 413 — Request Entity Too Large, returns Error
- 415 — JSON error ( JsonError ), returns Error
Changes the value of the selected key in the key-value pair, deletes a key by setting the key value to null , changes expiration time of a key-value pair. If synchronization of keyval zones in a cluster is enabled, deletes a key only on a target cluster node. Expiration time in milliseconds can be specified for a key-value pair with the expire parameter which overrides the timeout parameter of the keyval_zone directive.
httpKeyvalZoneKeyValue (HTTP Keyval Shared Memory Zone, required) A new value for the key is specified in the JSON format.
- 204 — Success
- 400 — Invalid JSON ( KeyvalFormatError ), key required ( KeyvalFormatError ), keyval timeout is not enabled ( KeyvalFormatError ), only one key can be updated ( KeyvalFormatError ), reading request body failed BodyReadError ), returns Error
- 404 — Keyval not found ( KeyvalNotFound ), keyval key not found ( KeyvalKeyNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 413 — Request Entity Too Large, returns Error
- 415 — JSON error ( JsonError ), returns Error
Deletes all key-value pairs from the HTTP keyval shared memory zone. If synchronization of keyval zones in a cluster is enabled, empties the keyval zone only on a target cluster node.
- 204 — Success
- 404 — Keyval not found ( KeyvalNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/stream/
- GET — Return list of stream-related endpoints
Returns a list of first level stream endpoints.
- 200 — Success, returns an array of strings
- 404 — Unknown version ( UnknownVersion ), returns Error
/stream/server_zones/
- GET — Return status of all stream server zones
Returns status information for each stream server zone.
fields ( string , optional) Limits which fields of server zones will be output. If the “ fields ” value is empty, then only server zone names will be output.
- 200 — Success, returns a collection of «Stream Server Zone» objects for all stream server zones
- 404 — Unknown version ( UnknownVersion ), returns Error
/stream/server_zones/ Parameters common for all methods: streamServerZoneName ( string , required) The name of a stream server zone.
- GET — Return status of a stream server zone
Returns status of a particular stream server zone.
fields ( string , optional) Limits which fields of the server zone will be output.
- 200 — Success, returns Stream Server Zone
- 404 — Server zone not found ( ServerZoneNotFound ), unknown version ( UnknownVersion ), returns Error
Resets statistics of accepted and discarded connections, sessions, received and sent bytes, counters of SSL handshakes and session reuses in a particular stream server zone.
- 204 — Success
- 404 — Server zone not found ( ServerZoneNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/stream/limit_conns/
- GET — Return status of all stream limit_conn zones
Returns status information for each stream limit_conn zone.
fields ( string , optional) Limits which fields of limit_conn zones will be output. If the “ fields ” value is empty, then only zone names will be output.
- 200 — Success, returns a collection of «Stream Connections Limiting» objects for all stream limit conns
- 404 — Unknown version ( UnknownVersion ), returns Error
/stream/limit_conns/ Parameters common for all methods: streamLimitConnZoneName ( string , required) The name of a limit_conn zone.
- GET — Return status of an stream limit_conn zone
Returns status of a particular stream limit_conn zone.
fields ( string , optional) Limits which fields of the limit_conn zone will be output.
- 200 — Success, returns Stream Connections Limiting
- 404 — limit_conn not found ( LimitConnNotFound ), unknown version ( UnknownVersion ), returns Error
Resets the connection limiting statistics.
- 204 — Success
- 404 — limit_conn not found ( LimitConnNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/stream/upstreams/
- GET — Return status of all stream upstream server groups
Returns status of each stream upstream server group and its servers.
fields ( string , optional) Limits which fields of upstream server groups will be output. If the “ fields ” value is empty, only names of upstreams will be output.
- 200 — Success, returns a collection of «Stream Upstream» objects for all stream upstreams
- 404 — Unknown version ( UnknownVersion ), returns Error
/stream/upstreams// Parameters common for all methods: streamUpstreamName ( string , required) The name of a stream upstream server group.
- GET — Return status of a stream upstream server group
Returns status of a particular stream upstream server group and its servers.
fields ( string , optional) Limits which fields of the upstream server group will be output.
- 200 — Success, returns Stream Upstream
- 400 — Upstream is static ( UpstreamStatic ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
Resets the statistics for each upstream server in an upstream server group.
- 204 — Success
- 400 — Upstream is static ( UpstreamStatic ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/stream/upstreams//servers/ Parameters common for all methods: streamUpstreamName ( string , required) The name of an upstream server group.
- GET — Return configuration of all servers in a stream upstream server group
Returns configuration of each server in a particular stream upstream server group.
- 200 — Success, returns an array of Stream Upstream Servers
- 400 — Upstream is static ( UpstreamStatic ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
Adds a new server to a stream upstream server group. Server parameters are specified in the JSON format.
postStreamUpstreamServer (Stream Upstream Server, required) Address of a new server and other optional parameters in the JSON format. The “ ID ”, “ backup ”, and “ service ” parameters cannot be changed.
- 201 — Created, returns Stream Upstream Server
- 400 — Upstream is static ( UpstreamStatic ), invalid “ parameter ” value ( UpstreamConfFormatError ), missing “ server ” argument ( UpstreamConfFormatError ), unknown parameter “ name ” ( UpstreamConfFormatError ), nested object or list ( UpstreamConfFormatError ), “ error ” while parsing ( UpstreamBadAddress ), no port in server “ host ” ( UpstreamBadAddress ), service upstream “ host ” may not have port ( UpstreamBadAddress ), service upstream “ host ” requires domain name ( UpstreamBadAddress ), invalid “ weight ” ( UpstreamBadWeight ), invalid “ max_conns ” ( UpstreamBadMaxConns ), invalid “ max_fails ” ( UpstreamBadMaxFails ), invalid “ fail_timeout ” ( UpstreamBadFailTimeout ), invalid “ slow_start ” ( UpstreamBadSlowStart ), “ service ” is empty ( UpstreamBadService ), no resolver defined to resolve ( UpstreamConfNoResolver ), upstream “ name ” has no backup ( UpstreamNoBackup ), upstream “ name ” memory exhausted ( UpstreamOutOfMemory ), reading request body failed BodyReadError ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 409 — Entry exists ( EntryExists ), returns Error
- 415 — JSON error ( JsonError ), returns Error
/stream/upstreams//servers/ Parameters common for all methods: streamUpstreamName ( string , required) The name of the upstream server group. streamUpstreamServerId ( string , required) The ID of the server.
- GET — Return configuration of a server in a stream upstream server group
Returns configuration of a particular server in the stream upstream server group.
- 200 — Success, returns Stream Upstream Server
- 400 — Upstream is static ( UpstreamStatic ), invalid server ID ( UpstreamBadServerId ), returns Error
- 404 — Unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), server with ID “ id ” does not exist ( UpstreamServerNotFound ), returns Error
Modifies settings of a particular server in a stream upstream server group. Server parameters are specified in the JSON format.
patchStreamUpstreamServer (Stream Upstream Server, required) Server parameters, specified in the JSON format. The “ ID ”, “ backup ”, and “ service ” parameters cannot be changed.
- 200 — Success, returns Stream Upstream Server
- 400 — Upstream is static ( UpstreamStatic ), invalid “ parameter ” value ( UpstreamConfFormatError ), unknown parameter “ name ” ( UpstreamConfFormatError ), nested object or list ( UpstreamConfFormatError ), “ error ” while parsing ( UpstreamBadAddress ), invalid “ server ” argument ( UpstreamBadAddress ), no port in server “ host ” ( UpstreamBadAddress ), invalid server ID ( UpstreamBadServerId ), invalid “ weight ” ( UpstreamBadWeight ), invalid “ max_conns ” ( UpstreamBadMaxConns ), invalid “ max_fails ” ( UpstreamBadMaxFails ), invalid “ fail_timeout ” ( UpstreamBadFailTimeout ), invalid “ slow_start ” ( UpstreamBadSlowStart ), reading request body failed BodyReadError ), “ service ” is empty ( UpstreamBadService ), server “ ID ” address is immutable ( UpstreamServerImmutable ), server “ ID ” weight is immutable ( UpstreamServerWeightImmutable ), upstream “ name ” memory exhausted ( UpstreamOutOfMemory ), returns Error
- 404 — Server with ID “ id ” does not exist ( UpstreamServerNotFound ), unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 415 — JSON error ( JsonError ), returns Error
Removes a server from a stream server group.
- 200 — Success, returns an array of Stream Upstream Servers
- 400 — Upstream is static ( UpstreamStatic ), invalid server ID ( UpstreamBadServerId ), server “ id ” not removable ( UpstreamServerImmutable ), returns Error
- 404 — Server with ID “ id ” does not exist ( UpstreamServerNotFound ), unknown version ( UnknownVersion ), upstream not found ( UpstreamNotFound ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/stream/keyvals/
- GET — Return key-value pairs from all stream keyval zones
Returns key-value pairs for each stream keyval shared memory zone.
fields ( string , optional) If the “ fields ” value is empty, then only stream keyval zone names will be output.
- 200 — Success, returns a collection of «Stream Keyval Shared Memory Zone» objects for all stream keyvals
- 404 — Unknown version ( UnknownVersion ), returns Error
/stream/keyvals/ Parameters common for all methods: streamKeyvalZoneName ( string , required) The name of a stream keyval shared memory zone.
- GET — Return key-value pairs from a stream keyval zone
Returns key-value pairs stored in a particular stream keyval shared memory zone.
key ( string , optional) Get a particular key-value pair from the stream keyval zone.
- 200 — Success, returns Stream Keyval Shared Memory Zone
- 404 — Keyval not found ( KeyvalNotFound ), keyval key not found ( KeyvalKeyNotFound ), unknown version ( UnknownVersion ), returns Error
Adds a new key-value pair to the stream keyval shared memory zone. Several key-value pairs can be entered if the stream keyval shared memory zone is empty.
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. Expiration time in milliseconds can be specified for a key-value pair with the expire parameter which overrides the timeout parameter of the keyval_zone directive.
- 201 — Created
- 400 — Invalid JSON ( KeyvalFormatError ), invalid key format ( KeyvalFormatError ), key required ( KeyvalFormatError ), keyval timeout is not enabled ( KeyvalFormatError ), only one key can be added ( KeyvalFormatError ), reading request body failed BodyReadError ), returns Error
- 404 — Keyval not found ( KeyvalNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 409 — Entry exists ( EntryExists ), key already exists ( KeyvalKeyExists ), returns Error
- 413 — Request Entity Too Large, returns Error
- 415 — JSON error ( JsonError ), returns Error
Changes the value of the selected key in the key-value pair, deletes a key by setting the key value to null , changes expiration time of a key-value pair. If synchronization of keyval zones in a cluster is enabled, deletes a key only on a target cluster node. Expiration time is specified in milliseconds with the expire parameter which overrides the timeout parameter of the keyval_zone directive.
streamKeyvalZoneKeyValue (Stream Keyval Shared Memory Zone, required) A new value for the key is specified in the JSON format.
- 204 — Success
- 400 — Invalid JSON ( KeyvalFormatError ), key required ( KeyvalFormatError ), keyval timeout is not enabled ( KeyvalFormatError ), only one key can be updated ( KeyvalFormatError ), reading request body failed BodyReadError ), returns Error
- 404 — Keyval not found ( KeyvalNotFound ), keyval key not found ( KeyvalKeyNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
- 413 — Request Entity Too Large, returns Error
- 415 — JSON error ( JsonError ), returns Error
Deletes all key-value pairs from the stream keyval shared memory zone. If synchronization of keyval zones in a cluster is enabled, empties the keyval zone only on a target cluster node.
- 204 — Success
- 404 — Keyval not found ( KeyvalNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/stream/zone_sync/
- GET — Return sync status of a node
Returns synchronization status of a cluster node.
- 200 — Success, returns Stream Zone Sync Node
- 404 — Unknown version ( UnknownVersion ), returns Error
/resolvers/
- GET — Return status for all resolver zones
Returns status information for each resolver zone.
fields ( string , optional) Limits which fields of resolvers statistics will be output.
- 200 — Success, returns a collection of «Resolver Zone» objects for all resolvers
- 404 — Unknown version ( UnknownVersion ), returns Error
/resolvers/ Parameters common for all methods: resolverZoneName ( string , required) The name of a resolver zone.
- GET — Return statistics of a resolver zone
Returns statistics stored in a particular resolver zone.
fields ( string , optional) Limits which fields of the resolver zone will be output (requests, responses, or both).
- 200 — Success, returns Resolver Zone
- 404 — Resolver zone not found ( ResolverZoneNotFound ), unknown version ( UnknownVersion ), returns Error
Resets statistics in a particular resolver zone.
- 204 — Success
- 404 — Resolver zone not found ( ResolverZoneNotFound ), unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
/ssl
- GET — Return SSL statistics
Returns SSL statistics.
fields ( string , optional) Limits which fields of SSL statistics will be output.
- 200 — Success, returns SSL
- 404 — Unknown version ( UnknownVersion ), returns Error
Resets counters of SSL handshakes and session reuses.
- 204 — Success
- 404 — Unknown version ( UnknownVersion ), returns Error
- 405 — Method disabled ( MethodDisabled ), returns Error
Response Objects
General information about nginx: 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 the ISO 8601 format with millisecond resolution. timestamp ( string ) Current time in the ISO 8601 format with millisecond resolution. 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.
respawned ( integer ) The total number of abnormally terminated and respawned child processes.
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.
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. no_common_protocol ( integer ) The number of SSL handshakes failed because of no common protocol. no_common_cipher ( integer ) The number of SSL handshakes failed because of no shared cipher. handshake_timeout ( integer ) The number of SSL handshakes failed because of a timeout. peer_rejected_cert ( integer ) The number of failed SSL handshakes when nginx presented the certificate to the client but it was rejected with a corresponding alert message. verify_failures SSL certificate verification errors no_cert ( integer ) A client did not provide the required certificate. expired_cert ( integer ) An expired or not yet valid certificate was presented by a client. revoked_cert ( integer ) A revoked certificate was presented by a client. hostname_mismatch ( integer ) Server’s certificate doesn’t match the hostname. other ( integer ) Other SSL certificate verification errors.
Shared memory zone with slab allocator:
Shared memory zone with slab allocator 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
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.
total ( integer ) The total number of client requests. current ( integer ) The current number of client requests.
HTTP Server Zone:
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, the number of responses with status codes “ 1xx ”, “ 2xx ”, “ 3xx ”, “ 4xx ”, and “ 5xx ”, and the number of responses per each status code. 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. codes The number of responses per each status code. codeNumber ( integer ) The number of responses with this particular status code. 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. 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. no_common_protocol ( integer ) The number of SSL handshakes failed because of no common protocol. no_common_cipher ( integer ) The number of SSL handshakes failed because of no shared cipher. handshake_timeout ( integer ) The number of SSL handshakes failed because of a timeout. peer_rejected_cert ( integer ) The number of failed SSL handshakes when nginx presented the certificate to the client but it was rejected with a corresponding alert message. verify_failures SSL certificate verification errors no_cert ( integer ) A client did not provide the required certificate. expired_cert ( integer ) An expired or not yet valid certificate was presented by a client. revoked_cert ( integer ) A revoked certificate was presented by a client. other ( integer ) Other SSL certificate verification errors.
HTTP Location Zone:
requests ( integer ) The total number of client requests received from clients. responses The total number of responses sent to clients, the number of responses with status codes “ 1xx ”, “ 2xx ”, “ 3xx ”, “ 4xx ”, and “ 5xx ”, and the number of responses per each status code. 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. codes The number of responses per each status code. codeNumber ( integer ) The number of responses with this particular status code. 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.
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.
HTTP Connections Limiting:
passed ( integer ) The total number of connections that were neither limited nor accounted as limited. rejected ( integer ) The total number of connections that were rejected. rejected_dry_run ( integer ) The total number of connections accounted as rejected in the dry run mode.
HTTP Requests Rate Limiting:
passed ( integer ) The total number of requests that were neither limited nor accounted as limited. delayed ( integer ) The total number of requests that were delayed. rejected ( integer ) The total number of requests that were rejected. delayed_dry_run ( integer ) The total number of requests accounted as delayed in the dry run mode. rejected_dry_run ( integer ) The total number of requests accounted as rejected in the dry run mode.
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. 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. no_common_protocol ( integer ) The number of SSL handshakes failed because of no common protocol. handshake_timeout ( integer ) The number of SSL handshakes failed because of a timeout. peer_rejected_cert ( integer ) The number of failed SSL handshakes when nginx presented the certificate to the upstream server but it was rejected with a corresponding alert message. verify_failures SSL certificate verification errors expired_cert ( integer ) An expired or not yet valid certificate was presented by an upstream server. revoked_cert ( integer ) A revoked certificate was presented by an upstream server. hostname_mismatch ( integer ) Server’s certificate doesn’t match the hostname. other ( integer ) Other SSL certificate verification errors. max_conns ( integer ) The max_conns limit for the server. requests ( integer ) The total number of client requests forwarded to this server. responses 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. codes The number of responses per each status code. codeNumber ( integer ) The number of responses with this particular status code. total ( integer ) The total number of responses obtained from this server. 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 requests (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 ) How many times the server became unhealthy (state “ unhealthy ”). last_passed ( boolean ) Boolean indicating if the last health check request was successful and passed tests. downtime ( integer ) Total time the server was in the “ unavail ”, “ checking ”, and “ unhealthy ” states. downstart ( string ) The time when the server became “ unavail ”, “ checking ”, or “ unhealthy ”, in the ISO 8601 format with millisecond resolution. selected ( string ) The time when the server was last selected to process a request, in the ISO 8601 format with millisecond resolution. 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.
HTTP Upstream Server:
Dynamically configurable parameters of an HTTP upstream server: 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.
HTTP Keyval Shared Memory Zone:
Contents of an HTTP keyval shared memory zone when using the GET method.
HTTP Keyval Shared Memory Zone:
Contents of an HTTP keyval shared memory zone when using the POST or PATCH methods.
Stream Server Zone:
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. 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. no_common_protocol ( integer ) The number of SSL handshakes failed because of no common protocol. no_common_cipher ( integer ) The number of SSL handshakes failed because of no shared cipher. handshake_timeout ( integer ) The number of SSL handshakes failed because of a timeout. peer_rejected_cert ( integer ) The number of failed SSL handshakes when nginx presented the certificate to the client but it was rejected with a corresponding alert message. verify_failures SSL certificate verification errors no_cert ( integer ) A client did not provide the required certificate. expired_cert ( integer ) An expired or not yet valid certificate was presented by a client. revoked_cert ( integer ) A revoked certificate was presented by a client. other ( integer ) Other SSL certificate verification errors.
Stream Connections Limiting:
passed ( integer ) The total number of connections that were neither limited nor accounted as limited. rejected ( integer ) The total number of connections that were rejected. rejected_dry_run ( integer ) The total number of connections accounted as rejected in the dry run mode.
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. 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. no_common_protocol ( integer ) The number of SSL handshakes failed because of no common protocol. handshake_timeout ( integer ) The number of SSL handshakes failed because of a timeout. peer_rejected_cert ( integer ) The number of failed SSL handshakes when nginx presented the certificate to the upstream server but it was rejected with a corresponding alert message. verify_failures SSL certificate verification errors expired_cert ( integer ) An expired or not yet valid certificate was presented by an upstream server. revoked_cert ( integer ) A revoked certificate was presented by an upstream server. hostname_mismatch ( integer ) Server’s certificate doesn’t match the hostname. other ( integer ) Other SSL certificate verification errors. 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 ) How many times the server became unhealthy (state “ unhealthy ”). last_passed ( boolean ) Boolean indicating whether the last health check request was successful and passed tests. downtime ( integer ) Total time the server was in the “ unavail ”, “ checking ”, and “ unhealthy ” states. downstart ( string ) The time when the server became “ unavail ”, “ checking ”, or “ unhealthy ”, in the ISO 8601 format with millisecond resolution. selected ( string ) The time when the server was last selected to process a connection, in the ISO 8601 format with millisecond resolution. zombies ( integer ) The current number of servers removed from the group but still processing active client connections. zone ( string ) The name of the shared memory zone that keeps the group’s configuration and run-time state.
Stream Upstream Server:
Dynamically configurable parameters of a stream upstream server: 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.
Stream Keyval Shared Memory Zone:
Contents of a stream keyval shared memory zone when using the GET method.
Stream Keyval Shared Memory Zone:
Contents of a stream keyval shared memory zone when using the POST or PATCH methods.
Источник
This might help:
If you want to display your own page instead of the default error page provided by DotCloud, you have to use a few tricks.
First, note that this will only work for stacks that embed a Nginx server. For other stacks, DotCloud load balancers will be the only layer between your user and your app, and for now, it can only serve a default error page.
You need to tell Nginx to do all those things:
use a custom static page for 502 and 504 errors;
remap the error code to e.g. 500 (else, the DotCloud load balancers will serve the default 502 and 504 pages);
intercept the errors sent by the uwsgi/fastcgi (else, our custom static page won’t be used);
reduce the default timeout, so your timeout handler will kick in before the platform-wide timeout handler.
Assuming your error pages are in /static/502.html and /static/504.html, you can use the following nginx.conf snippets:
PHP:
fastcgi_read_timeout 10;
fastcgi_intercept_errors on;
error_page 502 =500 /static/502.html;
error_page 504 =500 /static/504.html;
Perl/Phython:
uwsgi_read_timeout 10;
uwsgi_intercept_errors on;
error_page 502 =500 /static/502.html;
error_page 504 =500 /static/504.html;
Ruby:
For Ruby applications, since Passenger will use error code 500, no rewriting is needed. The default Nginx configuration already provides a handler for that (errorpage 500 /static/500.html). Also, since Passenger does not expose a configuration variable to change the timeout, you cannot provide a custom 504 page.
Once you enable intercept_errors in Nginx, you can no longer generate your
own error pages for e.g. HTTP codes 500, 403, etc. You have to define static
pages for those errors in Nginx as well. This limitation will be lifted in a
future version of the services.
Source: http://docs.dotcloud.com/guides/5xx/
Otherwise, Check out this page on http://wiki.nginx.org/NginxVariableTutorialCn06 that provides a decent tutorial on it. [Although I recommend translating the page via google chrome…]
Skip to content
Обработка ошибки в Nginx иногда требует менять код ответа и направлять запросы в определенный location.
Ниже приведен фрагмент конфигурационного файла, позволяющий это делать.
Принципиальна в файле одна строка error_page 404 =200 /err_404.php;
За счет нее для всех запросов, заканчивающихся ошибкой 404 будет меняться код ответа сервера на 200. Затем запросы будут переадресовываться в блок err_404.php
В блоке в данном случае настроено проксирование в php-fpm. Но могут быть заданы любые другие правила.
server { listen 443 ssl http2; server_name example.com www.example.com; root /var/www/web/sites/example.com; index index.html index.htm index.php; ssl_certificate /etc/nginx/ssl/example.com.full.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384; ssl_ecdh_curve secp384r1; error_page 404 =200 /err_404.php; location = /err_404.php { root /var/www/web/sites/example.com; try_files $uri $uri/; fastcgi_pass 127.0.0.1:9001; fastcgi_index err_404.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_ignore_client_abort off; } location ~ .php$ { try_files $uri $uri/ =404; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_ignore_client_abort off; } location ~ /.ht { deny all; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location @error { return 500; } }
После сохранения конфигурационного файла и перезапуска веб-сервера код ответа можно проверить обратившись в терминале к сайту при помощь curl.
Также код ответа будет видно в консоли разработчика браузера.