Module ngx_http_core_module

优质
小牛编辑
135浏览
2023-12-01

Directives

syntax:aio on | off | sendfile;
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.

On FreeBSD, AIO is usable starting from FreeBSD 4.3. AIO can either be linked statically into a kernel:

options VFS_AIO

or loaded dynamically as a kernel loadable module:

kldload aio

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

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

and can safely be ignored.

The requirement to use the Giant lock with AIO is related to the fact that FreeBSD supports asynchronous calls aio_read() and aio_write() when working with sockets. However, since nginx only uses AIO for disk I/O, no problems should arise.

For AIO to work, needs to be disabled:

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

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

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

In this configuration, sendfile() is called with the SF_NODISKIO flag which causes it not to block on disk I/O and instead report back when the data are not in memory; nginx then initiates an asynchronous data load by reading one byte. The FreeBSD kernel then loads the first 128K bytes of a file into memory, however next reads will only load data in 16K chunks. This can be tuned using the directive.

On Linux, AIO is usable starting from kernel version 2.6.22; plus, it is also necessary to enable , otherwise reading will be blocking:

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

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

syntax:alias path;
default:
context:location

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

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

the request of “/i/top.gif” will be responded with the file /data/w3/images/top.gif.

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 directive instead:

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

syntax:chunked_transfer_encoding on | off;
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 though the standard requires it.

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

Sets buffer size for reading client request body. In case request body is larger than the buffer, the whole body or only its part is written to a . 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 on | clean | off;
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 on | off;
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 path [level1 [level2 [level3]]];
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 underneath the specified directory. For example, in the following configuration

client_body_temp_path /spool/nginx/client_temp 1 2;

a temporary file might look like this:

/spool/nginx/client_temp/7/45/00000123457

syntax:client_body_timeout time;
default:
client_body_timeout 60s;
context:http, server, location

Defines a timeout for reading client request body. A timeout is only set 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 client error 408 (Request Time-out) is returned.

syntax:client_header_buffer_size 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 do not fit entirely into this buffer then larger buffers are allocated, configured by the directive.

syntax:client_header_timeout time;
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 client error 408 (Request Time-out) is returned.

syntax:client_max_body_size size;
default:
client_max_body_size 1m;
context:http, server, location

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

syntax:connection_pool_size size;
default:
connection_pool_size 256;
context:http, server

Allows to fine tune per-connection memory allocations. This directive has minimal impact on performance, and should not generally be used.

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

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

syntax:directio size | off;
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 (Mac OS X), or the directio() function (Solaris), when reading files that are larger than or equal to the specified size. It automatically disables (0.7.15) the use of for a given request. It could be useful for serving large files:

directio 4m;

or when using on Linux.

syntax:directio_alignment size;
default:
directio_alignment 512;
context:http, server, location

This directive appeared in version 0.8.11.

Sets an alignment for . 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 off; disable_symlinks on | if_not_owner [from=part];
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 (parameters on and if_not_owner), all components of the pathname are normally checked. Checking of symbolic links in the initial part of the pathname may be avoided by also specifying the from=part parameter. In this case, symbolic links are checked only from the component of the pathname following the specified initial part. If a value is not an initial part of the checked pathname, the whole pathname is checked as if this parameter was not specified at all. If a value fully matches the 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. This includes modern versions of FreeBSD, Linux, and Solaris.

Parameters on and if_not_owner add a processing overhead.

On systems that do not support opening directories for search only, the use of these parameters requires that worker processes have read permissions for all checked directories.

The ngx_http_autoindex_module, ngx_http_random_index_module, and ngx_http_dav_module modules currently ignore this directive.

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

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

Example:

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

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

error_page 404 =200 /empty.gif;

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

error_page 404 = /404.php;

It is also possible to use redirects for error processing:

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

In this case, the response code 302 is returned to the client. It can only be changed to one of the redirect status codes (301, 302, 303, and 307).

If there is no need to change URI during internal redirection it is possible to pass error processing into a named location:

location / {
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

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

syntax:etag on | off;
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 a configuration file context in which the HTTP server directives are specified.

syntax:if_modified_since off | exact | before;
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 “If-Modified-Since” request header field is ignored (0.7.34);
exact
exact match;
before
modification time of a response is less than or equal to the time in the “If-Modified-Since” request header field.

syntax:ignore_invalid_headers on | off;
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 directive).

A directive can be specified on the level in a default server. In this case, its value will cover all virtual servers listening on the same address and port.

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 , index, random_index, and 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 and by the ngx_http_addition_module module directives;
  • requests changed by the rewrite directive.

Example:

error_page 404 /404.html;

location /404.html {
    internal;
}

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

syntax:keepalive_disable none | browser ...;
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, after seeing a POST request. The value safari disables keep-alive connections with Safari and Safari-like browsers on Mac OS X and Mac OS X-like operating systems. The value none enables keep-alive connections with all browsers.

Prior to version 1.1.18, the value safari matched all Safari and Safari-like browsers on all operating systems, and keep-alive connections with them were disabled by default.

syntax:keepalive_requests number;
default:
keepalive_requests 100;
context:http, server, location

This directive appeared in version 0.8.0.

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

syntax:keepalive_timeout timeout [header_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 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 understood by Mozilla and Konqueror. MSIE will close keep-alive connection in about 60 seconds.

syntax:large_client_header_buffers number size;
default:
large_client_header_buffers 4 8k;
context:http, server

Sets the maximum number and size of buffers used when reading large client request header. A request line cannot exceed the size of one buffer, or the client error 414 (Request-URI Too Large) is returned. A request header field cannot exceed the size of one buffer as well, or the client error 400 (Bad Request) is returned. 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 freed.

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

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

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

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

syntax:limit_rate rate;
default:
limit_rate 0;
context:http, server, location, if in location

Rate limits the transmission of a response to a client. The rate is specified in bytes per second. The value 0 disables rate limiting. The limit is set per request, so if a client simultaneously opens two connections, an overall rate will be twice as much as the specified limit.

Rate limit can also be set in the $limit_rate variable. It may be useful in cases where rate should be limited depending on a certain condition:

server {

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

    ...
}

In addition, rate limit can also be set in the “X-Accel-Limit-Rate” header field of a proxied server response. This ability can be disabled using the proxy_ignore_headers and fastcgi_ignore_headers directives.

syntax:limit_rate_after size;
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.

Example:

location /flv/ {
    flv;
    limit_rate_after 500k;
    limit_rate       50k;
}

syntax:lingering_close off | on | always;
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 and 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 breaks the protocol and should not be used under normal circumstances.

syntax:lingering_time time;
default:
lingering_time 30s;
context:http, server, location

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

syntax:lingering_timeout time;
default:
lingering_timeout 5s;
context:http, server, location

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

syntax:listen address[:port] [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [ssl] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]]; listen port [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [ssl] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]]; listen unix:path [default_server] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ssl] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
default:
listen *:80 | *:8000;
context:server

Sets an address and a port for IP, or a path for a UNIX-domain socket, on which the server will accept requests. Only one of address or port may 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 [fe80::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 directive is not present then either the *:80 is used if nginx runs with 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.

A listen directive can have several additional parameters specific to socket-related system calls. They can be specified in any listen directive, but only once for the given address:port pair.

In versions prior to 0.8.21, they could only be specified in the listen directive along with the default parameter.

setfib=number
this parameter (0.8.44) sets an associated routing table, FIB (the SO_SETFIB option) for the listening socket. This currently works only on FreeBSD.
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 and Mac OS X, and to 511 on other platforms.
rcvbuf=size
sets receive buffer size (the SO_RCVBUF option) for the listening socket.
sndbuf=size
sets send buffer size (the SO_SNDBUF option) for the listening socket.
accept_filter=filter
sets the name of accept filter (the SO_ACCEPTFILTER option) for the listening socket that filters incoming connections before presenting them to accept(). This works only on FreeBSD and NetBSD 5.0+. Acceptable values are dataready and httpready.
deferred
instructs to use a deferred accept() (the TCP_DEFER_ACCEPT socket option) on Linux.
bind
instructs to make a separate bind() call for a given address:port pair. This is because nginx will bind() only to *:port if there are several listen directives with the same port but different addresses, and one of the listen directives listens on all addresses for the given port (*:port). It should be noted that in this case a getsockname() system call will be made to determine an address that accepted a connection. If parameters backlog, rcvbuf, sndbuf, accept_filter, deferred, or so_keepalive are used then for a given address:port pair a separate bind() call will always be made.
ipv6only=on|off
this parameter (0.7.42) determines (via the IPV6_V6ONLY socket option) whether 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.
ssl
this parameter (0.7.14) does not relate to socket-related system calls, but allows to specify 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.
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 set to the value “on”, the SO_KEEPALIVE socket option is turned on for the socket. If set to the value “off”, the SO_KEEPALIVE socket option is turned off for the socket. Some operating systems support tuning TCP keepalive parameters on a per-socket basis using the TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT socket options. On such systems (currently, Linux 2.4+, NetBSD 5+, and FreeBSD 9.0-STABLE) they can be configured using the keepidle, keepintvl, and keepcnt parameters. One or two parameters may be omitted, in which case the system default setting for the corresponding socket option will be in effect. For example,
so_keepalive=30m::10
will set idle timeout (TCP_KEEPIDLE) to 30 minutes, leave probe interval (TCP_KEEPINTVL) at its system default, and set probes count (TCP_KEEPCNT) to 10 probes.

Example:

listen 127.0.0.1 default_server accept_filter=dataready backlog=1024;

syntax:location [ = | ~ | ~* | ^~ ] uri { ... } location @name { ... }
default:
context:server, location

Sets a configuration based on a request URI.

The matching is performed against a normalized URI, after decoding a text encoded in the “%XX” form, resolving references to relative path components “.” and “..”, and possible 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 by prepending them with the “~*” modifier (for case-insensitive matching), or with the “~” modifier (for case-sensitive matching). To find a location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the most specific one is searched. Then regular expressions are checked, in the order of their appearance in a configuration file. A 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 a configuration of the most specific prefix location is used.

Locations can be nested, with some exceptions mentioned below.

For case-insensitive operating systems such as Mac OS X and Cygwin, matching with prefix strings ignores a case (0.7.7). However, comparison is limited to one-byte locales.

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

If the most specific 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 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.

syntax:log_not_found on | off;
default:
log_not_found on;
context:http, server, location

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

syntax:log_subrequest on | off;
default:
log_subrequest off;
context:http, server, location

Enables or disables logging of subrequests into the access_log.

syntax:max_ranges number;
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, there is no limit. The value of zero disables the byte-range support completely.

syntax:merge_slashes on | off;
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 prefix string and regular expressions location matching. 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 off the compression.

A directive can be specified on the level in a default server. In this case, its value will cover all virtual servers listening on the same address and port.

syntax:msie_padding on | off;
default:
msie_padding on;
context:http, server, location

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

syntax:msie_refresh on | off;
default:
msie_refresh off;
context:http, server, location

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

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

Configures a cache that can store:

  • open file descriptors, their sizes and modification times;
  • directory lookups;
  • file lookup errors, such as “file not found”, “no read permission”, and so on.
    Caching of errors should be enabled separately by the 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 get removed;
inactive
defines a time, after which an element gets removed from the cache if there were no accesses to it 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 on | off;
default:
open_file_cache_errors off;
context:http, server, location

Enables or disables caching of file lookup errors by .

syntax:open_file_cache_min_uses number;
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 directive, after which a file descriptor will remain open in the cache.

syntax:open_file_cache_valid time;
default:
open_file_cache_valid 60s;
context:http, server, location

Sets a time after which elements should be validated.

syntax:optimize_server_names on | off;
default:
optimize_server_names off;
context:http, server

This directive is made obsolete by the directive.

syntax:port_in_redirect on | off;
default:
port_in_redirect on;
context:http, server, location

Enables or disables specifying the port in redirects issued by nginx.

The use of a primary server name in redirects is controlled by the directive.

syntax:postpone_output size;
default:
postpone_output 1460;
context:http, server, location

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

syntax:read_ahead size;
default:
read_ahead 0;
context:http, server, location

Sets the amount of pre-reading when working with files, in the kernel.

On Linux, the posix_fadvise(0, 0, 0, POSIX_FADV_SEQUENTIAL) system call is used, so the size parameter is ignored.

On FreeBSD, the fcntl(O_READAHEAD, size) system call is used, supported in FreeBSD 9.0-CURRENT. FreeBSD 7 needs to be patched.

syntax:recursive_error_pages on | off;
default:
recursive_error_pages off;
context:http, server, location

Enables or disables doing several redirects using the directive. There is a on a number of such redirects.

syntax:request_pool_size size;
default:
request_pool_size 4k;
context:http, server

Allows to fine tune per-request memory allocations. This directive has minimal impact on performance, and should not generally be used.

syntax:reset_timedout_connection on | off;
default:
reset_timedout_connection off;
context:http, server, location

Enables or disables resetting of timed out connections. The reset is performed as follows: before closing a socket, the SO_LINGER option is set on it with a timeout value of 0. When the socket is closed, a client is sent TCP RST, and all memory occupied by this socket is freed. This avoids keeping of an already closed socket with filled buffers for a long time, in a FIN_WAIT1 state.

It should be noted that timed out keep-alive connections are still closed normally.

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

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

resolver 127.0.0.1 [::1]:5353;

An address can be specified as a domain name or IP address, and an optional port (1.3.1, 1.2.2). If port is not specified, the port 53 is used. Name servers are queried in a round-robin fashion.

Before version 1.1.7, only a single name server could be configured. Specifying name servers using IPv6 addresses is supported starting from versions 1.3.1 and 1.2.2.

By default, nginx caches answers using the TTL value of a response. An optional valid parameter allows to override 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.

syntax:resolver_timeout time;
default:
resolver_timeout 30s;
context:http, server, location

Sets a timeout for name resolution, for example:

resolver_timeout 5s;

syntax:root path;
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;
}

/i/top.gif” will be responded with the file /data/w3/i/top.gif.

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 need to be modified, the directive should be used.

syntax:satisfy all | any;
default:
satisfy all;
context:http, server, location

Allows access if all or any of the ngx_http_access_module or ngx_http_auth_basic_module modules grant access.

Example:

location / {
    satisfy any;

    allow 192.168.1.0/32;
    deny  all;

    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}

syntax:satisfy_any on | off;
default:
satisfy_any off;
context:http, server, location

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

syntax:send_lowat size;
default:
send_lowat 0;
context:http, server, location

If 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, with the specified size.

This directive is ignored on Linux, Solaris, and Windows.

syntax:send_timeout time;
default:
send_timeout 60s;
context:http, server, location

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

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

Enables or disables the use of sendfile().

syntax:sendfile_max_chunk size;
default:
sendfile_max_chunk 0;
context:http, server, location

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

syntax:server { ... }
default:
context:http

Sets a configuration for the virtual server. There is no clean separation between IP-based (based on the IP address) and name-based (based on the “Host” request header field) virtual servers. Instead, the directives describe all addresses and ports that should accept connections for a server, and the directive lists all server names. Example configurations are provided in the “How nginx processes a request” document.

syntax:server_name name ...;
default:
server_name "";
context:server

Sets names of the 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 (“*”) to replace 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 above mentioned names can be combined:

server {
    server_name .example.com;
}

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

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

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

server {
    server_name ~^(www\.)?(.+)$;

    location / {
        root /sites/$2;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

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

server {
    server_name ~^(www\.)?(?<domain>.+)$;

    location / {
        root /sites/$domain;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

If the parameter equals “$hostname” (0.9.4), the machine’s hostname is substituted.

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.

When searching for a virtual server by name, if name matches more than one of the specified variants, e.g. both wildcard name and regular expression match, the first matching variant will be chosen, in the following order of precedence:

  1. exact name
  2. longest wildcard name starting with an asterisk, e.g. “*.example.com
  3. longest wildcard name ending with an asterisk, e.g. “mail.*
  4. first matching regular expression (in order of appearance in a configuration file)

Detailed description of server names is provided in a separate Server names document.

syntax:server_name_in_redirect on | off;
default:
server_name_in_redirect off;
context:http, server, location

Enables or disables the use of the primary server name, specified by the directive, in redirects issued by nginx. When disabled, the name from the “Host” request header field is used. If this field is not present, an IP address of the server is used.

The use of a port in redirects is controlled by the directive.

syntax:server_names_hash_bucket_size size;
default:
server_names_hash_bucket_size 32|64|128;
context:http

Sets the bucket size for the server names hash tables. Default value depends on the size of the processor’s cache line. Details of setting up hash tables are provided in a separate document.

syntax:server_names_hash_max_size size;
default:
server_names_hash_max_size 512;
context:http

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

syntax:server_tokens on | off;
default:
server_tokens on;
context:http, server, location

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

syntax:tcp_nodelay on | off;
default:
tcp_nodelay on;
context:http, server, location

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

syntax:tcp_nopush on | off;
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. Options are enabled only when is used. Enabling the option allows to

  • send the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.*;
  • send a file in full packets.

syntax:try_files file ... uri; try_files file ... =code;
default:
context:server, location

Checks the existence of files in the specified order, and uses the first found file for request processing; the processing is performed in the current context. A path to the file is constructed from the file parameter according to the and directives. It is possible to check the directory 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 by 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. As of version 0.7.51, the last parameter can also be a code:

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

Example when 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 map 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, try the following:

location /download/ {
    types        { }
    default_type application/octet-stream;
}

syntax:types_hash_bucket_size size;
default:
types_hash_bucket_size 32|64|128;
context:http, server, location

Sets the bucket size for the types hash tables. Default value depends on the size of the processor’s cache line. Details of setting up hash tables are provided in a separate document.

syntax:types_hash_max_size size;
default:
types_hash_max_size 1024;
context:http, server, location

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

syntax:underscores_in_headers on | off;
default:
underscores_in_headers off;
context:http, server

Enables or disables the use of underscores in client request header fields. When disabled, request header fields whose names contain underscores are marked as invalid and are subject to the directive.

A directive can be specified on the level in a default server. In this case, its value will cover all virtual servers listening on the same address and port.

syntax:variables_hash_bucket_size size;
default:
variables_hash_bucket_size 64;
context:http

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

syntax:variables_hash_max_size size;
default:
variables_hash_max_size 512;
context:http

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

Embedded Variables

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

$arg_name
argument name in the request line
$args
arguments in the request line
$binary_remote_addr
client address in a binary form, value’s length is always 4 bytes
$body_bytes_sent
number of bytes sent to a client, not counting the response header; this variable is compatible with the “%B” parameter of the mod_log_config Apache module
$bytes_sent
number of bytes sent to a client (1.3.8, 1.2.5)
$connection
connection serial number (1.3.8, 1.2.5)
$connection_requests
current number of requests made through a connection (1.3.8, 1.2.5)
$content_length
“Content-Length” request header field
$content_type
“Content-Type” request header field
$cookie_name
the name cookie
$document_root
or directive’s value for the current request
$document_uri
same as $uri
$host
“Host” request header field, or the server name matching a request if this field is not present
$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 allows for response rate limiting; see
$msec
current time in seconds with a milliseconds resolution (1.3.9, 1.2.6)
$nginx_version
nginx version
$pid
PID of the worker process
$query_string
same as $args
$realpath_root
an absolute pathname corresponding to the or directive’s value for the current request, with all symbolic links resolved to real paths
$remote_addr
client address
$remote_port
client port
$remote_user
user name supplied with the Basic authentication
$request
full original request line
$request_body
request body

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

$request_body_file
name of a temporary file with the request body

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

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

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

$server_name
name of the server which accepted a request
$server_port
port of the server which accepted a request
$server_protocol
request protocol, usually “HTTP/1.0” or “HTTP/1.1
$status
response status (1.3.2, 1.2.2)
$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space
information about the client TCP connection; available on systems that support the TCP_INFO socket option
$uri
current URI in request,

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