<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_index_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_index_module

Example Configuration
Directives
     index

The ngx_http_index_module module processes requests
ending with the slash character (‘/’).
Such requests can also be processed by the
ngx_http_autoindex_module
and
ngx_http_random_index_module
modules.

Example Configuration

location / {
    index index.$geo.html index.html;
}

Directives

            Syntax:

            index file ...;

            Default:

index index.html;

            Context:

            http, server, location

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

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

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

location = / {
    index index.html;
}

location / {
    ...
}

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


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_internal_redirect_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_internal_redirect_module

Example Configuration
Directives
     internal_redirect

The ngx_http_internal_redirect_module module (1.23.4) allows
making an internal redirect.
In contrast to
rewriting URIs,
the redirection is made after checking
request and
connection processing limits,
and access limits.

This module is available as part of our
commercial subscription.

Example Configuration

limit_req_zone $jwt_claim_sub zone=jwt_sub:10m rate=1r/s;

server {
    location / {
        auth_jwt          "realm";
        auth_jwt_key_file key.jwk;

        internal_redirect @rate_limited;
    }

    location @rate_limited {
        internal;

        limit_req  zone=jwt_sub burst=10;
        proxy_pass http://backend;
    }
}

The example implements
per-user
rate limiting.
Implementation without internal_redirect
is vulnerable to DoS attacks by unsigned JWTs, as normally the
limit_req
check is performed
before
auth_jwt check.
Using internal_redirect
allows reordering these checks.

Directives

            Syntax:

            internal_redirect uri;

            Default:

            —

            Context:

            server, location

Sets the URI for internal redirection of the request.
It is also possible to use a
named location
instead of the URI.
The uri value can contain variables.
If the uri value is empty,
then the redirect will not be made.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_js_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_js_module

Example Configuration
Directives
     js_body_filter
     js_access
     js_content
     js_context_reuse
     js_engine
     js_fetch_buffer_size
     js_fetch_ciphers
     js_fetch_max_response_buffer_size
     js_fetch_protocols
     js_fetch_timeout
     js_fetch_trusted_certificate
     js_fetch_verify
     js_fetch_verify_depth
     js_fetch_proxy
     js_fetch_keepalive
     js_fetch_keepalive_requests
     js_fetch_keepalive_time
     js_fetch_keepalive_timeout
     js_header_filter
     js_import
     js_include
     js_load_http_native_module
     js_path
     js_periodic
     js_preload_object
     js_set
     js_shared_dict_zone
     js_var
Request Argument

The ngx_http_js_module module is used to implement
location and variable handlers
in njs —
a subset of the JavaScript language.

Download and install instructions are available
here.

Example Configuration

The example works since
0.4.0.

http {
    js_import http.js;

    js_set $foo     http.foo;
    js_set $summary http.summary;
    js_set $hash    http.hash;

    resolver 10.0.0.1;

    server {
        listen 8000;

        location / {
            add_header X-Foo $foo;
            js_content http.baz;
        }

        location = /summary {
            return 200 $summary;
        }

        location = /hello {
            js_content http.hello;
        }

        # since 0.7.0
        location = /fetch {
            js_content                   http.fetch;
            js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem;
        }

        # since 0.7.0
        location = /crypto {
            add_header Hash $hash;
            return     200;
        }
    }
}

The http.js file:

function foo(r) {
    r.log("hello from foo() handler");
    return "foo";
}

function summary(r) {
    var a, s, h;

    s = "JS summary\n\n";

    s += "Method: " + r.method + "\n";
    s += "HTTP version: " + r.httpVersion + "\n";
    s += "Host: " + r.headersIn.host + "\n";
    s += "Remote Address: " + r.remoteAddress + "\n";
    s += "URI: " + r.uri + "\n";

    s += "Headers:\n";
    for (h in r.headersIn) {
        s += "  header '" + h + "' is '" + r.headersIn[h] + "'\n";
    }

    s += "Args:\n";
    for (a in r.args) {
        s += "  arg '" + a + "' is '" + r.args[a] + "'\n";
    }

    return s;
}

function baz(r) {
    r.status = 200;
    r.headersOut.foo = 1234;
    r.headersOut['Content-Type'] = "text/plain; charset=utf-8";
    r.headersOut['Content-Length'] = 15;
    r.sendHeader();
    r.send("nginx");
    r.send("java");
    r.send("script");

    r.finish();
}

function hello(r) {
    r.return(200, "Hello world!");
}

// since 0.7.0
async function fetch(r) {
    let results = await Promise.all([ngx.fetch('https://nginx.org/'),
                                     ngx.fetch('https://nginx.org/en/')]);

    r.return(200, JSON.stringify(results, undefined, 4));
}

// since 0.7.0
async function hash(r) {
    let hash = await crypto.subtle.digest('SHA-512', r.headersIn.host);
    r.setReturnValue(Buffer.from(hash).toString('hex'));
}

export default {foo, summary, baz, hello, fetch, hash};

Directives

            Syntax:

            js_body_filter module.function
[buffer_type=string | buffer];

            Default:

            —

            Context:

            location, if in location, limit_except

This directive appeared in version 0.5.2.

Sets an njs function as a response body filter.
The filter function is called for each data chunk of a response body
with the following arguments:

r

the HTTP request object

data

the incoming data chunk,
may be a string or Buffer
depending on the buffer_type value,
by default is a string.
Since 0.8.5, the
data value is implicitly converted to a valid UTF-8 string
by default.
For binary data, the buffer_type value
should be set to buffer.

flags

an object with the following properties:

last

a boolean value, true if data is a last buffer.

The filter function can pass its own modified version
of the input data chunk to the next body filter by calling
r.sendBuffer().
For example, to transform all the lowercase letters in the response body:

function filter(r, data, flags) {
    r.sendBuffer(data.toLowerCase(), flags);
}

If the filter function changes the length of the response body, the
“Content-Length” response header (if present) should be cleared
in js_header_filter
to enforce chunked transfer encoding:

example.conf:
 location /foo {
     # proxy_pass http://localhost:8080;

    js_header_filter main.clear_content_length;
    js_body_filter   main.filter;
 }

example.js:
 function clear_content_length(r) {
     delete r.headersOut['Content-Length'];
 }

To stop filtering and pass the data chunks to the client
without calling js_body_filter,
r.done()
can be used.
For example, to prepend some data to the response body:

function prepend(r, data, flags) {
    r.sendBuffer("XXX");
    r.sendBuffer(data, flags);
    r.done();
}

As the js_body_filter handler
returns its result immediately, it supports
only synchronous operations.
Thus, asynchronous operations such as
r.subrequest()
or
setTimeout()
are not supported.

The directive can be specified inside the
if block
since 0.7.7.

            Syntax:

            js_access module.function;

            Default:

            —

            Context:

            location, if in location, limit_except

This directive appeared in version 0.9.9.

Sets an njs function as a handler in the
access phase.
Asynchronous operations such as
r.subrequest(),
ngx.fetch(),
and setTimeout()
are supported.

A handler that returns without calling
r.return()
or
r.decline()
grants access.
To deny access or send a custom response (for example, a redirect),
the handler may call
r.return().
To make the handler express no opinion, deferring the decision to other
access checkers under
satisfy any,
the handler may call
r.decline().

For example:

example.conf:
 location /protected/ {
     js_access  main.auth;
     proxy_pass http://upstream;
 }

example.js:
 async function auth(r) {
     let reply = await ngx.fetch('http://authsvc/check', {
         headers: {Authorization: r.headersIn.Authorization}
     });

     if (reply.status != 200) {
         r.return(401);
         return;
     }
 }

 export default {auth};

            Syntax:

            js_content module.function;

            Default:

            —

            Context:

            location, if in location, limit_except

Sets an njs function as a location content handler.
Since 0.4.0,
a module function can be referenced.

The directive can be specified inside the
if block
since 0.7.7.

            Syntax:

            js_context_reuse number;

            Default:

js_context_reuse 128;

            Context:

            http, server, location

This directive appeared in version 0.8.6.

Sets a maximum number of JS context to be reused for
QuickJS engine.
Each context is used for a single request.
The finished context is put into a pool of reusable contexts.
If the pool is full, the context is destroyed.

            Syntax:

            js_engine njs | qjs;

            Default:

js_engine njs;

            Context:

            http, server, location

This directive appeared in version 0.8.6.

Sets a JavaScript engine
to be used for njs scripts.
The njs parameter sets the njs engine, also used by default.
The qjs parameter sets the QuickJS engine.

            Syntax:

            js_fetch_buffer_size size;

            Default:

js_fetch_buffer_size 16k;

            Context:

            http, server, location

This directive appeared in version 0.7.4.

Sets the size of the buffer used for reading and writing
with Fetch API.

            Syntax:

            js_fetch_ciphers ciphers;

            Default:

js_fetch_ciphers HIGH:!aNULL:!MD5;

            Context:

            http, server, location

This directive appeared in version 0.7.0.

Specifies the enabled ciphers for HTTPS requests
with Fetch API.
The ciphers are specified in the format understood by the
OpenSSL library.

The full list can be viewed using the
“openssl ciphers” command.

            Syntax:

            js_fetch_max_response_buffer_size size;

            Default:

js_fetch_max_response_buffer_size 1m;

            Context:

            http, server, location

This directive appeared in version 0.7.4.

Sets the maximum size of the response received
with Fetch API.

            Syntax:

            js_fetch_protocols
    [TLSv1]
    [TLSv1.1]
    [TLSv1.2]
    [TLSv1.3];

            Default:

js_fetch_protocols TLSv1 TLSv1.1 TLSv1.2;

            Context:

            http, server, location

This directive appeared in version 0.7.0.

Enables the specified protocols for HTTPS requests
with Fetch API.

            Syntax:

            js_fetch_timeout time;

            Default:

js_fetch_timeout 60s;

            Context:

            http, server, location

This directive appeared in version 0.7.4.

Defines a timeout for reading and writing
for Fetch API.
The timeout is set only between two successive read/write operations,
not for the whole response.
If no data is transmitted within this time, the connection is closed.

            Syntax:

            js_fetch_trusted_certificate file;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.7.0.

Specifies a file with trusted CA certificates in the PEM format
used to
verify
the HTTPS certificate
with Fetch API.

            Syntax:

            js_fetch_verify on | off;

            Default:

js_fetch_verify on;

            Context:

            http, server, location

This directive appeared in version 0.7.4.

Enables or disables verification of the HTTPS server certificate
with Fetch API.

            Syntax:

            js_fetch_verify_depth number;

            Default:

js_fetch_verify_depth 100;

            Context:

            http, server, location

This directive appeared in version 0.7.0.

Sets the verification depth in the HTTPS server certificates chain
with Fetch API.

            Syntax:

            js_fetch_proxy url;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.9.4.

Configures a forward proxy URL
with Fetch API.
The url supports the HTTP scheme only
and can contain optional user credentials
in the format http://[user:password@]host:port
for Basic authentication.
Supports both HTTP and HTTPS connections to destination servers.
If the url is empty, proxy routing is disabled.
The parameter value can contain variables.

Example:

location /fetch {
    js_fetch_proxy http://user:pass@proxy.example.com:3128;
    js_content main.fetch_handler;
}

            Syntax:

            js_fetch_keepalive connections;

            Default:

js_fetch_keepalive 0;

            Context:

            http, server, location

This directive appeared in version 0.9.2.

Activates the cache for connections to destination servers.
When the value is greater than 0,
enables keepalive connections for
Fetch API.

The connections parameter sets the maximum number of idle
keepalive connections to destination servers that are preserved in the cache
of each worker process.
When this number is exceeded, the least recently used connections are closed.

Example:

location /fetch {
    js_fetch_keepalive 32;
    js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem;
    js_content main.fetch_handler;
}

            Syntax:

            js_fetch_keepalive_requests number;

            Default:

js_fetch_keepalive_requests 1000;

            Context:

            http, server, location

This directive appeared in version 0.9.2.

Sets the maximum number of requests that can be served through one keepalive
connection with Fetch API.
After the maximum number of requests is 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.

            Syntax:

            js_fetch_keepalive_time time;

            Default:

js_fetch_keepalive_time 1h;

            Context:

            http, server, location

This directive appeared in version 0.9.2.

Limits the maximum time during which requests can be processed through one
keepalive connection with Fetch API.
After this time is reached, the connection is closed following the subsequent
request processing.

            Syntax:

            js_fetch_keepalive_timeout time;

            Default:

js_fetch_keepalive_timeout 60s;

            Context:

            http, server, location

This directive appeared in version 0.9.2.

Sets a timeout during which an idle keepalive connection to a destination server
will stay open with Fetch API.

            Syntax:

            js_header_filter module.function;

            Default:

            —

            Context:

            location, if in location, limit_except

This directive appeared in version 0.5.1.

Sets an njs function as a response header filter.
The directive allows changing arbitrary header fields of a response header.

As the js_header_filter handler
returns its result immediately, it supports
only synchronous operations.
Thus, asynchronous operations such as
r.subrequest()
or
setTimeout()
are not supported.

The directive can be specified inside the
if block
since 0.7.7.

            Syntax:

            js_import module.js |
export_name from module.js;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.4.0.

Imports a module that implements location and variable handlers in njs.
The export_name is used as a namespace
to access module functions.
If the export_name is not specified,
the module name will be used as a namespace.

js_import http.js;

Here, the module name http is used as a namespace
while accessing exports.
If the imported module exports foo(),
http.foo is used to refer to it.

Several js_import directives can be specified.

When js_import is specified inside a
location,
the imported modules are visible only if no JavaScript code
has been invoked earlier in the request.
A single VM is created per request when a
js_set variable is first accessed
or when a js_content, js_header_filter,
js_body_filter, or js_access handler
is first invoked.
The VM is cloned from the configuration scope active at that moment,
and all subsequent JavaScript invocations within the request reuse it.
Thus, if any of the above is referenced before the request is mapped
to its final location, for example from a server-level
set,
the VM is bound to the import set of the outer scope, and modules
imported in the matched location will not be visible.
To avoid this, declare such imports in a common parent scope.

The directive can be specified on the
server and location level
since 0.7.7.

            Syntax:

            js_include file;

            Default:

            —

            Context:

            http

Specifies a file that implements location and variable handlers in njs:

nginx.conf:
js_include http.js;
location   /version {
    js_content version;
}

http.js:
function version(r) {
    r.return(200, njs.version);
}

The directive was made obsolete in version
0.4.0
and was removed in version
0.7.1.
The js_import directive should be used instead.

            Syntax:

            js_load_http_native_module path [as name];

            Default:

            —

            Context:

            main

This directive appeared in version 0.9.5.

Loads a native module
(shared library) for use in HTTP JavaScript code.
The directive is
QuickJS-only
and is not available when using the njs built-in JavaScript engine.

The path parameter
specifies the absolute path to the shared library file.
The optional as name parameter
provides an alias name for importing the module in JavaScript code.
If not specified, the module can be imported using its filename.

Example:

js_load_http_native_module /path/to/mylib.so;
js_load_http_native_module /path/to/other.so as myalias;

http {
    js_import main.js;
    # ... rest of http configuration
}

In JavaScript code:

// Import by filename
import * as mylib from 'mylib.so';

// Import by alias
import * as myalias from 'myalias';

// Use exported functions
let result = mylib.add(5, 10);

For security reasons, this directive is only allowed
in the main configuration context.
Native modules run with full process privileges;
use absolute paths and ensure proper code review.

            Syntax:

            js_path
path;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.3.0.

Sets an additional path for njs modules.

The directive can be specified on the
server and location level
since 0.7.7.

            Syntax:

            js_periodic module.function
        [interval=time]
        [jitter=number]
        [worker_affinity=mask];

            Default:

            —

            Context:

            location

This directive appeared in version 0.8.1.

Specifies a content handler to run at regular interval.
The handler receives a
session object
as its first argument,
it also has access to global objects such as
ngx.

The optional interval parameter
sets the interval between two consecutive runs,
by default, 5 seconds.

The optional jitter parameter sets the time within which
the location content handler will be randomly delayed,
by default, there is no delay.

By default, the js_handler is executed on worker process 0.
The optional worker_affinity parameter
allows specifying particular worker processes
where the location content handler should be executed.
Each worker process set is represented by a bitmask of allowed worker processes.
The all mask allows the handler to be executed
in all worker processes.

Example:

example.conf:

location @periodics {
    # to be run at 1 minute intervals in worker process 0
    js_periodic main.handler interval=60s;

    # to be run at 1 minute intervals in all worker processes
    js_periodic main.handler interval=60s worker_affinity=all;

    # to be run at 1 minute intervals in worker processes 1 and 3
    js_periodic main.handler interval=60s worker_affinity=0101;

    resolver 10.0.0.1;
    js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem;
}

example.js:

async function handler(s) {
    let reply = await ngx.fetch('https://nginx.org/en/docs/njs/');
    let body = await reply.text();

    ngx.log(ngx.INFO, body);
}

            Syntax:

            js_preload_object name.json |
name from file.json;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.7.8.

Preloads an
immutable object
at configure time.
The name is used as a name of the global variable
though which the object is available in njs code.
If the name is not specified,
the file name will be used instead.

js_preload_object map.json;

Here, the map is used as a name
while accessing the preloaded object.

Several js_preload_object directives can be specified.

            Syntax:

            js_set
    $variable
    module.function
    [nocache];

            Default:

            —

            Context:

            http, server, location

Sets an njs function
for the specified variable.
Since 0.4.0,
a module function can be referenced.

The function is called when
the variable is referenced for the first time for a given request.
The exact moment depends on a
phase
at which the variable is referenced.
This can be used to perform some logic
not related to variable evaluation.
For example, if the variable is referenced only in the
log_format directive,
its handler will not be executed until the log phase.
This handler can be used to do some cleanup
right before the request is freed.

Since 0.8.6,
if an optional argument nocache is specified,
the handler is called every time it is referenced.
Due to current limitations
of the rewrite module,
when a nocache variable is referenced by the
set directive
its handler should always return a fixed-length value.

As the js_set handler
returns its result immediately, it supports
only synchronous operations.
Thus, asynchronous operations such as
r.subrequest()
or
setTimeout()
are not supported.

The directive can be specified on the
server and location level
since 0.7.7.

            Syntax:

            js_shared_dict_zone
    zone=name:size
    [timeout=time]
    [type=string|number]
    [evict]
    [state=file];

            Default:

            —

            Context:

            http

This directive appeared in version 0.8.0.

Sets the name and size of the shared memory zone
that keeps the
key-value dictionary
shared between worker processes.

By default the shared dictionary uses a string as a key and a value.
The optional type parameter
allows redefining the value type to number.

The optional timeout parameter sets
the time in milliseconds
after which all shared dictionary entries are removed from the zone.
If some entries require a different removal time, it can be set
with the timeout argument of the
add,
incr, and
set
methods
(0.8.5).

The optional evict parameter removes the oldest
key-value pair when the zone storage is exhausted.

The optional state parameter specifies a file
that keeps the shared dictionary state
in JSON format and makes it persistent across nginx restarts
(0.9.1).

Example:

example.conf:
    # Creates a 1Mb dictionary with string values,
    # removes key-value pairs after 60 seconds of inactivity:
    js_shared_dict_zone zone=foo:1M timeout=60s;

    # Creates a 512Kb dictionary with string values,
    # forcibly removes oldest key-value pairs when the zone is exhausted:
    js_shared_dict_zone zone=bar:512K timeout=30s evict;

    # Creates a 32Kb permanent dictionary with number values:
    js_shared_dict_zone zone=num:32k type=number;

    # Creates a 1Mb dictionary with string values and persistent state:
    js_shared_dict_zone zone=persistent:1M state=/tmp/dict.json;

example.js:
    function get(r) {
        r.return(200, ngx.shared.foo.get(r.args.key));
    }

    function set(r) {
        r.return(200, ngx.shared.foo.set(r.args.key, r.args.value));
    }

    function del(r) {
        r.return(200, ngx.shared.bar.delete(r.args.key));
    }

    function increment(r) {
        r.return(200, ngx.shared.num.incr(r.args.key, 2));
    }

            Syntax:

            js_var $variable [value];

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.5.3.

Declares
a writable
variable.
The value can contain text, variables, and their combination.
The variable is not overwritten after a redirect
unlike variables created with the
set directive.

The directive can be specified on the
server and location level
since 0.7.7.

Request Argument

Each HTTP njs handler receives one argument, a request
object.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_keyval_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_keyval_module

Example Configuration
Directives
     keyval
     keyval_zone

The ngx_http_keyval_module module (1.13.3) creates variables
with values taken from key-value pairs managed by the
API
or a variable (1.15.10) that can also be set with
njs.

This module is available as part of our
commercial subscription.

Example Configuration

http {

    keyval_zone zone=one:32k state=/var/lib/nginx/state/one.keyval;
    keyval $arg_text $text zone=one;
    ...
    server {
        ...
        location / {
            return 200 $text;
        }

        location /api {
            api write=on;
        }
    }
}

Directives

            Syntax:

            keyval
    key
    $variable
    zone=name;

            Default:

            —

            Context:

            http

Creates a new $variable whose value
is looked up by the key in the key-value database.
Matching rules are defined by the
type parameter of the
keyval_zone directive.
The database is stored in a shared memory zone
specified by the zone parameter.

            Syntax:

            keyval_zone
    zone=name:size
    [state=file]
    [timeout=time]
    [type=string|ip|prefix]
    [sync];

            Default:

            —

            Context:

            http

Sets the name and size of the shared memory zone
that keeps the key-value database.
Key-value pairs are managed by the
API.

The optional state parameter specifies a file
that keeps the current state of the key-value database in the JSON format
and makes it persistent across nginx restarts.
Changing the file content directly should be avoided.

Examples:

keyval_zone zone=one:32k state=/var/lib/nginx/state/one.keyval; # path for Linux
keyval_zone zone=one:32k state=/var/db/nginx/state/one.keyval;  # path for FreeBSD

The optional timeout parameter (1.15.0) sets
the time after which key-value pairs are removed from the zone.

The optional type parameter (1.17.1) activates
an extra index optimized for matching the key of a certain type
and defines matching rules when evaluating
a keyval $variable.

The index is stored in the same shared memory zone
and thus requires additional storage.

type=string

default, no index is enabled;
variable lookup is performed using exact match
of the record key and a search key

type=ip

the search key is the textual representation of IPv4 or IPv6 address
or CIDR range;
to match a record key, the search key must belong to a subnet
specified by a record key or exactly match an IP address

type=prefix

variable lookup is performed using prefix match
of a record key and a search key (1.17.5);
to match a record key, the record key must be a prefix of the search key

The optional sync parameter (1.15.0) enables
synchronization
of the shared memory zone.
The synchronization requires the
timeout parameter to be set.

If the synchronization is enabled, removal of key-value pairs (no matter
one
or
all)
will be performed only on a target cluster node.
The same key-value pairs on other cluster nodes
will be removed upon timeout.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_limit_conn_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_limit_conn_module

Example Configuration
Directives
     limit_conn
     limit_conn_dry_run
     limit_conn_log_level
     limit_conn_status
     limit_conn_zone
     limit_zone
Embedded Variables

The ngx_http_limit_conn_module module is used to
limit the number of connections per the defined key, in
particular, the number of connections from a single IP address.

Not all connections are counted.
A connection is counted only if it has a request being processed by the server
and the whole request header has already been read.

Example Configuration

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    ...

    server {

        ...

        location /download/ {
            limit_conn addr 1;
        }

Directives

            Syntax:

            limit_conn zone number;

            Default:

            —

            Context:

            http, server, location

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

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location /download/ {
        limit_conn addr 1;
    }

allow only one connection per an IP address at a time.

In HTTP/2 and HTTP/3,
each concurrent request is considered a separate connection.

There could be several limit_conn directives.
For example, the following configuration will limit the number
of connections to the server per a client IP and, at the same time,
the total number of connections to the virtual server:

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;

server {
    ...
    limit_conn perip 10;
    limit_conn perserver 100;
}

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

            Syntax:

            limit_conn_dry_run on | off;

            Default:

limit_conn_dry_run off;

            Context:

            http, server, location

This directive appeared in version 1.17.6.

Enables the dry run mode.
In this mode, the number of connections is not limited, however,
in the shared memory zone, the number of excessive connections is accounted
as usual.

            Syntax:

            limit_conn_log_level
info |
notice |
warn |
error;

            Default:

limit_conn_log_level error;

            Context:

            http, server, location

This directive appeared in version 0.8.18.

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

            Syntax:

            limit_conn_status code;

            Default:

limit_conn_status 503;

            Context:

            http, server, location

This directive appeared in version 1.3.15.

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

            Syntax:

            limit_conn_zone
    key
    zone=name:size;

            Default:

            —

            Context:

            http

Sets parameters for a shared memory zone
that will keep states for various keys.
In particular, the state includes the current number of connections.
The key can contain text, variables, and their combination.
Requests with an empty key value are not accounted.

Prior to version 1.7.6, a key could contain exactly one variable.

Usage example:

limit_conn_zone $binary_remote_addr zone=addr:10m;

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

Additionally, as part of our
commercial subscription,
the
status information
for each such shared memory zone can be
obtained or
reset
with the API since 1.17.7.

            Syntax:

            limit_zone
    name
    $variable
    size;

            Default:

            —

            Context:

            http

This directive was made obsolete in version 1.1.8
and was removed in version 1.7.6.
An equivalent limit_conn_zone directive
with a changed syntax should be used instead:

limit_conn_zone
$variable
zone=name:size;

Embedded Variables

$limit_conn_status

keeps the result of limiting the number of connections (1.17.6):
PASSED,
REJECTED, or
REJECTED_DRY_RUN


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_limit_req_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_limit_req_module

Example Configuration
Directives
     limit_req
     limit_req_dry_run
     limit_req_log_level
     limit_req_status
     limit_req_zone
Embedded Variables

The ngx_http_limit_req_module module (0.7.21) is used
to limit the request processing rate per a defined key,
in particular, the processing rate of requests coming
from a single IP address.
The limitation is done using the “leaky bucket” method.

Example Configuration

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

    ...

    server {

        ...

        location /search/ {
            limit_req zone=one burst=5;
        }

Directives

            Syntax:

            limit_req
    zone=name
    [burst=number]
    [nodelay |
     delay=number];

            Default:

            —

            Context:

            http, server, location

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

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

server {
    location /search/ {
        limit_req zone=one burst=5;
    }

allow not more than 1 request per second at an average,
with bursts not exceeding 5 requests.

If delaying of excessive requests while requests are being limited is not
desired, the parameter nodelay should be used:

limit_req zone=one burst=5 nodelay;

The delay parameter (1.15.7) specifies a limit
at which excessive requests become delayed.
Default value is zero, i.e. all excessive requests are delayed.

There could be several limit_req directives.
For example, the following configuration will limit the processing rate
of requests coming from a single IP address and, at the same time,
the request processing rate by the virtual server:

limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
limit_req_zone $server_name zone=perserver:10m rate=10r/s;

server {
    ...
    limit_req zone=perip burst=5 nodelay;
    limit_req zone=perserver burst=10;
}

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

            Syntax:

            limit_req_dry_run on | off;

            Default:

limit_req_dry_run off;

            Context:

            http, server, location

This directive appeared in version 1.17.1.

Enables the dry run mode.
In this mode, requests processing rate is not limited, however,
in the shared memory zone, the number of excessive requests is accounted
as usual.

            Syntax:

            limit_req_log_level
info |
notice |
warn |
error;

            Default:

limit_req_log_level error;

            Context:

            http, server, location

This directive appeared in version 0.8.18.

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

            Syntax:

            limit_req_status code;

            Default:

limit_req_status 503;

            Context:

            http, server, location

This directive appeared in version 1.3.15.

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

            Syntax:

            limit_req_zone
    key
    zone=name:size
    rate=rate
    [sync];

            Default:

            —

            Context:

            http

Sets parameters for a shared memory zone
that will keep states for various keys.
In particular, the state stores the current number of excessive requests.
The key can contain text, variables, and their combination.
Requests with an empty key value are not accounted.

Prior to version 1.7.6, a key could contain exactly one variable.

Usage example:

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

Here, the states are kept in a 10 megabyte zone “one”, and an
average request processing rate for this zone cannot exceed
1 request per second.

A client IP address serves as a key.
Note that instead of $remote_addr, the
$binary_remote_addr variable is used here.
The $binary_remote_addr variable’s size
is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses.
The stored state always occupies
64 bytes on 32-bit platforms and 128 bytes on 64-bit platforms.
One megabyte zone can keep about 16 thousand 64-byte states
or about 8 thousand 128-byte states.

If the zone storage is exhausted, the least recently used state is removed.
If even after that a new state cannot be created, the request is terminated with
an error.

The rate is specified in requests per second (r/s).
If a rate of less than one request per second is desired,
it is specified in request per minute (r/m).
For example, half-request per second is 30r/m.

The sync parameter (1.15.3) enables
synchronization
of the shared memory zone.

The sync parameter is available as part of our
commercial subscription.

Additionally, as part of our
commercial subscription,
the
status information
for each such shared memory zone can be
obtained or
reset
with the API since 1.17.7.

Embedded Variables

$limit_req_status

keeps the result of limiting the request processing rate (1.17.6):
PASSED,
DELAYED,
REJECTED,
DELAYED_DRY_RUN, or
REJECTED_DRY_RUN


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_log_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_log_module

Example Configuration
Directives
     access_log
     log_format
     open_log_file_cache

The ngx_http_log_module module writes request logs
in the specified format.

Requests are logged in the context of a location where processing ends.
It may be different from the original location, if an
internal
redirect happens during request processing.

Example Configuration

log_format compression '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log compression buffer=32k;

Directives

            Syntax:

            access_log
    path
    [format
    [buffer=size]
    [gzip[=level]]
    [flush=time]
    [if=condition]];
access_log off;

            Default:

access_log logs/access.log combined;

            Context:

            http, server, location, if in location, limit_except

Sets the path, format, and configuration for a buffered log write.
Several logs can be specified on the same configuration level.
Logging to syslog
can be configured by specifying
the “syslog:” prefix in the first parameter.
The special value off cancels all
access_log directives on the current level.
If the format is not specified then the predefined
“combined” format is used.

If either the buffer or gzip
(1.3.10, 1.2.7)
parameter is used, writes to log will be buffered.

The buffer size must not exceed the size of an atomic write to a disk file.
For FreeBSD this size is unlimited.

When buffering is enabled, the data will be written to the file:

if the next log line does not fit into the buffer;

if the buffered data is older than specified by the flush
parameter (1.3.10, 1.2.7);

when a worker process is re-opening log
files or is shutting down.

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

Example:

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

For gzip compression to work, nginx must be built with the zlib library.

The file path can contain variables (0.7.6+),
but such logs have some constraints:

the user
whose credentials are used by worker processes should
have permissions to create files in a directory with
such logs;

buffered writes do not work;

the file is opened and closed for each log write.
However, since the descriptors of frequently used files can be stored
in a cache, writing to the old file
can continue during the time specified by the open_log_file_cache
directive’s valid parameter

during each log write the existence of the request’s
root directory
is checked, and if it does not exist the log is not
created.
It is thus a good idea to specify both
root
and access_log on the same configuration level:

server {
    root       /spool/vhost/data/$host;
    access_log /spool/vhost/logs/$host;
    ...

The if parameter (1.7.0) enables conditional logging.
A request will not be logged if the condition evaluates to “0”
or an empty string.
In the following example, the requests with response codes 2xx and 3xx
will not be logged:

map $status $loggable {
    ~^[23]  0;
    default 1;
}

access_log /path/to/access.log combined if=$loggable;

            Syntax:

            log_format
    name
    [escape=default|json|none]
    string ...;

            Default:

log_format combined "...";

            Context:

            http

Specifies log format.

The escape parameter (1.11.8) allows setting
json or default characters escaping
in variables, by default, default escaping is used.
The none value (1.13.10) disables escaping.

For default escaping,
characters “"”, “\”,
and other characters with values less than 32 (0.7.0) or above 126 (1.1.6)
are escaped as “\xXX”.
If the variable value is not found,
a hyphen (“-”) will be logged.

For json escaping,
all characters not allowed
in JSON strings
will be escaped:
characters “"” and
“\” are escaped as
“\"” and “\\”,
characters with values less than 32 are escaped as
“\n”,
“\r”,
“\t”,
“\b”,
“\f”, or
“\u00XX”.

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

$bytes_sent

the number of bytes sent to a client

$connection

connection serial number

$connection_requests

the current number of requests made through a connection (1.1.18)

$msec

time in seconds with a milliseconds resolution at the time of the log write

$pipe

“p” if request was pipelined, “.”
otherwise

$request_length

request length (including request line, header, and request body)

$request_time

request processing time in seconds with a milliseconds resolution;
time elapsed between the first bytes were read from the client and
the log write after the last bytes were sent to the client

$status

response status

$time_iso8601

local time in the ISO 8601 standard format

$time_local

local time in the Common Log Format

In the modern nginx versions variables
$status
(1.3.2, 1.2.2),
$bytes_sent
(1.3.8, 1.2.5),
$connection
(1.3.8, 1.2.5),
$connection_requests
(1.3.8, 1.2.5),
$msec
(1.3.9, 1.2.6),
$request_time
(1.3.9, 1.2.6),
$pipe
(1.3.12, 1.2.7),
$request_length
(1.3.12, 1.2.7),
$time_iso8601
(1.3.12, 1.2.7),
and
$time_local
(1.3.12, 1.2.7)
are also available as common variables.

Header lines sent to a client have the prefix
“sent_http_”, for example,
$sent_http_content_range.

The configuration always includes the predefined
“combined” format:

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

            Syntax:

            open_log_file_cache
max=N
[inactive=time]
[min_uses=N]
[valid=time];
open_log_file_cache off;

            Default:

open_log_file_cache off;

            Context:

            http, server, location

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

max

sets the maximum number of descriptors in a cache;
if the cache becomes full the least recently used (LRU)
descriptors are closed

inactive

sets the time after which the cached descriptor is closed
if there were no access during this time;
by default, 10 seconds

min_uses

sets the minimum number of file uses during the time
defined by the inactive parameter
to let the descriptor stay open in a cache;
by default, 1

valid

sets the time after which it should be checked that the file
still exists with the same name; by default, 60 seconds

off

disables caching

Usage example:

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


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_map_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_map_module

Example Configuration
Directives
     map
     map_hash_bucket_size
     map_hash_max_size

The ngx_http_map_module module creates variables
whose values depend on values of other variables.

Example Configuration

map $http_host $name {
    hostnames;

    default       0;

    example.com   1;
    *.example.com 1;
    example.org   2;
    *.example.org 2;
    .example.net  3;
    wap.*         4;
}

map $http_user_agent $mobile {
    default       0;
    "~Opera Mini" 1;
}

Directives

            Syntax:

            map
    string
    $variable { ... }

            Default:

            —

            Context:

            http

Creates a new variable whose value
depends on values of one or more of the source variables
specified in the first parameter.

Before version 0.9.0 only a single variable could be
specified in the first parameter.

Since variables are evaluated only when they are used, the mere declaration
even of a large number of “map” variables
does not add any extra costs to request processing.

Parameters inside the map block specify a mapping
between source and resulting values.

Source values are specified as strings or regular expressions (0.9.6).

Strings are matched ignoring the case.

A regular expression should either start from the “~”
symbol for a case-sensitive matching, or from the “~*”
symbols (1.0.4) for case-insensitive matching.
A regular expression can contain named and positional captures
that can later be used in other directives along with the
resulting variable.

If a source value matches one of the names of special parameters
described below, it should be prefixed with the “\” symbol.

The resulting value can contain text,
variable (0.9.0), and their combination (1.11.0).

The following special parameters are also supported:

default value

sets the resulting value if the source value matches none
of the specified variants.
When default is not specified, the default
resulting value will be an empty string.

hostnames

indicates that source values can be hostnames with a prefix or suffix mask:

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

The following two records

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

can be combined:

.example.com  1;

This parameter should be specified before the list of values.

include file

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

volatile

indicates that the variable is not cacheable (1.11.7).

The search is performed in the following order of priority
and terminates on the first matching variant:

the string value without a mask

the longest string value with a prefix mask,
e.g. “*.example.com”

the longest string value with a suffix mask,
e.g. “mail.*”

the first matching regular expression
(in order of appearance in the configuration file)

the default value

            Syntax:

            map_hash_bucket_size size;

            Default:

map_hash_bucket_size 32|64|128;

            Context:

            http

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

            Syntax:

            map_hash_max_size size;

            Default:

map_hash_max_size 2048;

            Context:

            http

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


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_memcached_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_memcached_module

Example Configuration
Directives
     memcached_allow_upstream
     memcached_bind
     memcached_bind_dynamic
     memcached_buffer_size
     memcached_connect_timeout
     memcached_gzip_flag
     memcached_next_upstream
     memcached_next_upstream_timeout
     memcached_next_upstream_tries
     memcached_pass
     memcached_read_timeout
     memcached_send_timeout
     memcached_socket_keepalive
Embedded Variables

The ngx_http_memcached_module module is used to obtain
responses from a memcached server.
The key is set in the $memcached_key variable.
A response should be put in memcached in advance by means
external to nginx.

Example Configuration

server {
    location / {
        set            $memcached_key "$uri?$args";
        memcached_pass host:11211;
        error_page     404 502 504 = @fallback;
    }

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

Directives

            Syntax:

            memcached_allow_upstream string ...;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 1.29.3.

Defines conditions under which access to a memcached server
is allowed or denied.
If all string parameters are not empty
and not equal to “0” then the access is allowed.
The conditions are evaluated each time
before a connection to a memcached server is established.
Parameter values can contain variables:

geo $upstream_last_addr $allow {
    volatile;
    10.10.0.0/24        1;
}

server {
    listen 127.0.0.1:8080;

    location / {
        memcached_pass           host:11211;
        memcached_allow_upstream $allow;
        ...
    }
}

This directive is available as part of our
commercial subscription.

            Syntax:

            memcached_bind
    address
    [transparent ] |
    off;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 0.8.22.

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

The transparent parameter (1.11.0) allows
outgoing connections to a memcached server originate
from a non-local IP address,
for example, from a real IP address of a client:

memcached_bind $remote_addr transparent;

In order for this parameter to work,
it is usually necessary to run nginx worker processes with the
superuser privileges.
On Linux it is not required (1.13.8) as if
the transparent parameter is specified, worker processes
inherit the CAP_NET_RAW capability from the master process.
It is also necessary to configure kernel routing table
to intercept network traffic from the memcached server.

            Syntax:

            memcached_bind_dynamic on | off;

            Default:

memcached_bind_dynamic off;

            Context:

            http, server, location

This directive appeared in version 1.29.3.

When enabled, makes the bind operation
at each connection attempt.

This directive is available as part of our
commercial subscription.

            Syntax:

            memcached_buffer_size size;

            Default:

memcached_buffer_size 4k|8k;

            Context:

            http, server, location

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

            Syntax:

            memcached_connect_timeout time;

            Default:

memcached_connect_timeout 60s;

            Context:

            http, server, location

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

            Syntax:

            memcached_gzip_flag flag;

            Default:

            —

            Context:

            http, server, location

This directive appeared in version 1.3.6.

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

            Syntax:

            memcached_next_upstream
    error |
    timeout |
    denied |
    invalid_response |
    not_found |
    off
    ...;

            Default:

memcached_next_upstream error timeout;

            Context:

            http, server, location

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

error

an error occurred while establishing a connection with the
server, passing a request to it, or reading the response header;

timeout

a timeout has occurred while establishing a connection with the
server, passing a request to it, or reading the response header;

denied

the server denied
the connection (1.29.3);

This parameter is available as part of our
commercial subscription.

invalid_response

a server returned an empty or invalid response;

not_found

a response was not found on the server;

off

disables passing a request to the next server.

One should bear in mind that passing a request to the next server is
only possible if nothing has been sent to a client yet.
That is, if an error or timeout occurs in the middle of the
transferring of a response, fixing this is impossible.

The directive also defines what is considered an
unsuccessful
attempt of communication with a server.
The cases of error, timeout,
denied and
invalid_response are always considered unsuccessful attempts,
even if they are not specified in the directive.
The case of not_found
is never considered an unsuccessful attempt.

Passing a request to the next server can be limited by
the number of tries
and by time.

            Syntax:

            memcached_next_upstream_timeout time;

            Default:

memcached_next_upstream_timeout 0;

            Context:

            http, server, location

This directive appeared in version 1.7.5.

Limits the time during which a request can be passed to the
next server.
The 0 value turns off this limitation.

            Syntax:

            memcached_next_upstream_tries number;

            Default:

memcached_next_upstream_tries 0;

            Context:

            http, server, location

This directive appeared in version 1.7.5.

Limits the number of possible tries for passing a request to the
next server.
The 0 value turns off this limitation.

            Syntax:

            memcached_pass address;

            Default:

            —

            Context:

            location, if in location

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

memcached_pass localhost:11211;

or as a UNIX-domain socket path:

memcached_pass unix:/tmp/memcached.socket;

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

            Syntax:

            memcached_read_timeout time;

            Default:

memcached_read_timeout 60s;

            Context:

            http, server, location

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

            Syntax:

            memcached_send_timeout time;

            Default:

memcached_send_timeout 60s;

            Context:

            http, server, location

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

            Syntax:

            memcached_socket_keepalive on | off;

            Default:

memcached_socket_keepalive off;

            Context:

            http, server, location

This directive appeared in version 1.15.6.

Configures the “TCP keepalive” behavior
for outgoing connections to a memcached server.
By default, the operating system’s settings are in effect for the socket.
If the directive is set to the value “on”, the
SO_KEEPALIVE socket option is turned on for the socket.

Embedded Variables

$memcached_key

Defines a key for obtaining response from a memcached server.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_mirror_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_mirror_module

Example Configuration
Directives
     mirror
     mirror_request_body

The ngx_http_mirror_module module (1.13.4) implements
mirroring of an original request
by creating background mirror subrequests.
Responses to mirror subrequests are ignored.

Example Configuration

location / {
    mirror /mirror;
    proxy_pass http://backend;
}

location = /mirror {
    internal;
    proxy_pass http://test_backend$request_uri;
}

Directives

            Syntax:

            mirror uri | off;

            Default:

mirror off;

            Context:

            http, server, location

Sets the URI to which an original request will be mirrored.
Several mirrors can be specified on the same configuration level.

            Syntax:

            mirror_request_body on | off;

            Default:

mirror_request_body on;

            Context:

            http, server, location

Indicates whether the client request body is mirrored.
When enabled, the client request body will be read
prior to creating mirror subrequests.
In this case, unbuffered client request body proxying
set by the
proxy_request_buffering,
fastcgi_request_buffering,
scgi_request_buffering,
and
uwsgi_request_buffering
directives will be disabled.

location / {
    mirror /mirror;
    mirror_request_body off;
    proxy_pass http://backend;
}

location = /mirror {
    internal;
    proxy_pass http://log_backend;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_mp4_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_mp4_module

Example Configuration
Directives
     mp4
     mp4_buffer_size
     mp4_max_buffer_size
     mp4_limit_rate
     mp4_limit_rate_after
     mp4_start_key_frame

The ngx_http_mp4_module module provides pseudo-streaming
server-side support for MP4 files.
Such files typically have the .mp4, .m4v,
or .m4a filename extensions.

Pseudo-streaming works in alliance with a compatible media player.
The player sends an HTTP request to the server with the start time
specified in the query string argument (named simply
start
and specified in seconds), and the server responds with the stream
such that its start position corresponds to the requested time,
for example:

http://example.com/elephants_dream.mp4?start=238.88

This allows performing a random seeking at any time, or starting playback
in the middle of the timeline.

To support seeking, H.264-based formats store metadata
in a so-called “moov atom”.
It is a part of the file that holds the index information for the
whole file.

To start playback, the player first needs to read metadata.
This is done by sending a special request with the
start=0 argument.
A lot of encoding software insert the metadata at
the end of the file.
This is suboptimal for pseudo-streaming, because the player
has to download the entire file before starting playback.
If the metadata are located at the beginning of the file,
it is enough for nginx to simply start sending back the file contents.
If the metadata are located at the end of the file,
nginx must read the entire file and prepare a new stream so that
the metadata come before the media data.
This involves some CPU, memory, and disk I/O overhead,
so it is a good idea to

prepare an original file for pseudo-streaming in advance,
rather than having nginx do this on every such request.

The module also supports the end argument of an HTTP request
(1.5.13) which sets the end point of playback.
The end argument can be specified with the
start argument
or separately:

http://example.com/elephants_dream.mp4?start=238.88&end=555.55

For a matching request with a non-zero
start or end
argument, nginx will read the metadata from the file, prepare the
stream with the requested time range, and send it to the client.
This has the same overhead as described above.

If the start argument points to
a non-key video frame,
the beginning of such video will be broken.
To fix this issue, the video
can be prepended with
the key frame before start point
and with all intermediate frames between them.
These frames will be hidden from playback
using an edit list (1.21.4).

If a matching request does not include the
start and end
arguments, there is no overhead, and the file is sent simply as a static
resource.
Some players also support byte-range requests, and thus do not require
this module.

This module is not built by default, it should be enabled with the
--with-http_mp4_module
configuration parameter.

If a third-party mp4 module was previously used, it should be disabled.

A similar pseudo-streaming support for FLV files is provided by the
ngx_http_flv_module module.

Example Configuration

location /video/ {
    mp4;
    mp4_buffer_size       1m;
    mp4_max_buffer_size   5m;
    mp4_limit_rate        on;
    mp4_limit_rate_after  30s;
}

Directives

            Syntax:

            mp4;

            Default:

            —

            Context:

            location

Turns on module processing in a surrounding location.

            Syntax:

            mp4_buffer_size size;

            Default:

mp4_buffer_size 512K;

            Context:

            http, server, location

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

            Syntax:

            mp4_max_buffer_size size;

            Default:

mp4_max_buffer_size 10M;

            Context:

            http, server, location

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

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

            Syntax:

            mp4_limit_rate
    on |
    off |
    factor;

            Default:

mp4_limit_rate off;

            Context:

            http, server, location

Limits the rate of response transmission to a client.
The rate is limited based on the average bitrate of the
MP4 file served.
To calculate the rate, the bitrate is multiplied by the specified
factor.
The special value “on” corresponds to the factor of 1.1.
The special value “off” 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.

This directive is available as part of our
commercial subscription.

            Syntax:

            mp4_limit_rate_after time;

            Default:

mp4_limit_rate_after 60s;

            Context:

            http, server, location

Sets the initial amount of media data (measured in playback time)
after which the further transmission of the response to a client
will be rate limited.

This directive is available as part of our
commercial subscription.

            Syntax:

            mp4_start_key_frame on | off;

            Default:

mp4_start_key_frame off;

            Context:

            http, server, location

This directive appeared in version 1.21.4.

Forces output video to always start with a key video frame.
If the start argument does not point to a key frame,
initial frames are hidden using an mp4 edit list.
Edit lists are supported by major players and browsers such as
Chrome, Safari, QuickTime and ffmpeg,
partially supported by Firefox.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_num_map_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_num_map_module

Example Configuration
Directives
     num_map

The ngx_http_num_map_module module (1.29.3)
creates variables whose values depend on numeric values
or numeric value ranges.

This module is available as part of our
commercial subscription.

Example Configuration

num_map $remote_port $port_allow {
    default    0;

    80         1;
    443        1;
    <=1023     0;
    8080-8090  1;
}

Directives

            Syntax:

            num_map
    [$number]
    $variable { ... }

            Default:

            —

            Context:

            http

Describes how the values of the specified variable depend on numeric values
or numeric value ranges.

Since variables are evaluated only when used, the mere existence
of even a large number of declared “num_map” variables
does not cause any extra costs for request processing.

Parameters inside the num_map block specify a mapping
between source and resulting values.

Source values are specified as numbers or as numeric ranges.

The following special parameters are also supported:

default

sets the resulting value if the source value matches none
of the specified variants.
When default is not specified, the default
resulting value will be an empty string.

include

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

volatile

indicates that the variable is not cacheable.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_oidc_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_oidc_module

Example Configuration
Directives
     oidc_provider
     auth_oidc
     issuer
     client_id
     client_secret
     config_url
     cookie_name
     extra_auth_args
     frontchannel_logout_uri
     pkce
     redirect_uri
     logout_uri
     post_logout_uri
     logout_token_hint
     scope
     session_store
     session_timeout
     ssl_crl
     ssl_trusted_certificate
     userinfo
Embedded Variables

The ngx_http_oidc_module module (1.27.4)
implements authentication as a Relying Party in OpenID Connect using the

Authorization Code Flow.

The module expects the OpenID Provider's configuration to be available via

metadata and requires dynamic
resolver.

The module can be combined with other access modules
via the satisfy directive.
Note that the module may still block requests even with
satisfy any;
as an OpenID Provider might not redirect the user back to nginx.

This module is available as part of our
commercial subscription.

Example Configuration

http {
    resolver 10.0.0.1;

    oidc_provider my_idp {
        issuer        "https://provider.domain";
        client_id     "unique_id";
        client_secret "unique_secret";
    }

    server {
        location / {
            auth_oidc my_idp;

            proxy_set_header username $oidc_claim_sub;
            proxy_pass       http://backend;
        }
    }
}

The example assumes that the
“https://<nginx-host>/oidc_callback”
Redirection URI is configured on the OpenID Provider's side.
The path can be customized with the redirect_uri directive.

Directives

            Syntax:

            oidc_provider name { ... }

            Default:

            —

            Context:

            http

Defines an OpenID Provider for use with the auth_oidc directive.

            Syntax:

            auth_oidc name | off;

            Default:

auth_oidc off;

            Context:

            http, server, location

Enables end user authentication with the
specified OpenID Provider.

Parameter value can contain variables (1.29.0).

The special value off cancels the effect
of the auth_oidc directive
inherited from the previous configuration level.

            Syntax:

            issuer URL;

            Default:

            —

            Context:

            oidc_provider

Sets the Issuer Identifier URL of the OpenID Provider;
required directive.
The URL must exactly match the value of “issuer”
in the OpenID Provider metadata
and requires the “https” scheme.

            Syntax:

            client_id string;

            Default:

            —

            Context:

            oidc_provider

Specifies the client ID of the Relying Party;
required directive.

            Syntax:

            client_secret string;

            Default:

            —

            Context:

            oidc_provider

Specifies a secret value
used to authenticate the Relying Party with the OpenID Provider.
The supported
authentication
methods are
client_secret_basic and
client_secret_post (1.29.3).
The method is selected based on the OpenID Provider metadata
with a preference to client_secret_basic.

            Syntax:

            config_url URL;

            Default:

config_url <issuer>/.well-known/openid-configuration;

            Context:

            oidc_provider

Sets a custom URL to retrieve the OpenID Provider metadata.

            Syntax:

            cookie_name name;

            Default:

cookie_name NGX_OIDC_SESSION;

            Context:

            oidc_provider

Sets the name of a session cookie.

            Syntax:

            extra_auth_args string;

            Default:

            —

            Context:

            oidc_provider

Sets additional query arguments for the
authentication
request URL.

extra_auth_args "display=page&prompt=login";

            Syntax:

            frontchannel_logout_uri uri;

            Default:

            —

            Context:

            oidc_provider

This directive appeared in version 1.29.3.

Defines the URI path for triggering
front-channel
logout.
For the logout request to be associated with a user session,
it must either include the module session cookie or provide
both the “iss” and “sid” arguments.
It is recommended to configure the OpenID Provider to set the
“iss” and “sid” arguments
when invoking this endpoint.

            Syntax:

            pkce on | off;

            Default:

            —

            Context:

            oidc_provider

This directive appeared in version 1.29.3.

Explicitly enables or disables PKCE.
By default, PKCE is automatically enabled
based on OpenID Provider metadata.

            Syntax:

            redirect_uri uri;

            Default:

redirect_uri /oidc_callback;

            Context:

            oidc_provider

Defines the Redirection URI path for post-authentication redirects
expected by the module from the OpenID Provider.
The uri must match the configuration on the Provider's side.

Absolute “https” URIs are supported since 1.29.0.

            Syntax:

            logout_uri uri;

            Default:

            —

            Context:

            oidc_provider

This directive appeared in version 1.29.0.

Defines the URI path for initiating session logout.
Upon session termination, the user is redirected to
Provider's
Logout Endpoint
or to the post logout page.
If neither is configured, the built-in post logout page is displayed.

            Syntax:

            post_logout_uri uri;

            Default:

            —

            Context:

            oidc_provider

This directive appeared in version 1.29.0.

Defines the path or absolute URI
to redirect the user to after the logout.
The uri must match the configuration on the Provider's side.
If the post logout page is served by NGINX,
the OIDC module shouldn't be enabled for this location:

http {
    oidc_provider my_idp {
        ...

        logout_uri      /logout;
        post_logout_uri /logged_out_page.html;
    }

    server {
        auth_oidc my_idp;

        location /logged_out_page.html {
            auth_oidc off;
        }
    }
}

            Syntax:

            logout_token_hint on | off;

            Default:

logout_token_hint off;

            Context:

            oidc_provider

This directive appeared in version 1.29.0.

Adds the
id_token_hint
argument to the
Provider's
Logout Endpoint
when redirecting user during logout.
This argument can be required by some OpenID Providers.

            Syntax:

            scope scope ...;

            Default:

scope openid;

            Context:

            oidc_provider

Sets requested scopes.
The openid scope is always required by OIDC.

            Syntax:

            session_store name;

            Default:

            —

            Context:

            oidc_provider

Specifies a custom
key-value database
that stores session data.
By default, an 8-megabyte key-value database named
oidc_default_store_<provider name>
is created automatically.

A separate key-value database should be configured for each Provider
to prevent session reuse across providers.

            Syntax:

            session_timeout time;

            Default:

session_timeout 8h;

            Context:

            oidc_provider

Sets a timeout after which the session is deleted, unless it was
refreshed.

            Syntax:

            ssl_crl file;

            Default:

            —

            Context:

            oidc_provider

Specifies a file with revoked certificates (CRL)
in the PEM format used to verify
the certificates of the OpenID Provider endpoints.
When using intermediate certificates, their CRLs should be
specified in the same file.

            Syntax:

            ssl_trusted_certificate file;

            Default:

ssl_trusted_certificate system CA bundle;

            Context:

            oidc_provider

Specifies a file with trusted CA certificates in the PEM format
used to verify
the certificates of the OpenID Provider endpoints.

            Syntax:

            userinfo on | off;

            Default:

userinfo off;

            Context:

            oidc_provider

This directive appeared in version 1.29.0.

Enables downloading of the
UserInfo
data and makes UserInfo claims available via the
$oidc_claim_name variables.

Embedded Variables

The ngx_http_oidc_module module supports embedded variables:

$oidc_id_token

ID token

$oidc_access_token

access token

$oidc_claim_name

top-level ID token or UserInfo claim

Nested claims can be fetched with the
auth_jwt module:

http {
    auth_jwt_claim_set $postal_code address postal_code;

    server {
        location / {
            auth_oidc my_idp;
            auth_jwt  off token=$oidc_id_token;

            proxy_set_header x-postal_code $postal_code;
            proxy_pass       http://backend;
        }
    }
}

$oidc_userinfo

UserInfo data in the JSON format (1.29.0)


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_perl_module</title><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="../../../css/style_en.css">

Planning your ingress-nginx migration? Start here:
kubernetes.nginx.org.

<input class="side-menu" type="checkbox" id="side-menu">

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_perl_module

Known Issues
Example Configuration
Directives
     perl
     perl_modules
     perl_require
     perl_set
Calling Perl from SSI
The $r Request Object Methods

The ngx_http_perl_module module is used to implement
location and variable handlers in Perl and insert Perl calls into SSI.

This module is not built by default, it should be enabled with the
--with-http_perl_module
configuration parameter.

This module requires
Perl version 5.6.1 or higher.
The C compiler should be compatible with the one used to build Perl.

Known Issues

The module is experimental, caveat emptor applies.

In order for Perl to recompile the modified modules during
reconfiguration, it should be built with the
-Dusemultiplicity=yes or
-Dusethreads=yes parameters.
Also, to make Perl leak less memory at run time,
it should be built with the
-Dusemymalloc=no parameter.
To check the values of these parameters in an already built
Perl (preferred values are specified in the example), run:

$ perl -V:usemultiplicity -V:usemymalloc
usemultiplicity='define';
usemymalloc='n';

Note that after rebuilding Perl with the new
-Dusemultiplicity=yes or
-Dusethreads=yes parameters,
all binary Perl modules will have to be rebuilt as well —
they will just stop working with the new Perl.

There is a possibility that the main process and then worker processes will
grow in size after every reconfiguration.
If the main process grows to an unacceptable size, the
live upgrade
procedure can be applied without changing the executable file.

While the Perl module is performing a long-running operation, such as
resolving a domain name, connecting to another server, or querying a database,
other requests assigned to the current worker process will not be processed.
It is thus recommended to perform only such operations
that have predictable and short execution time, such as
accessing the local file system.

Example Configuration

http {

    perl_modules perl/lib;
    perl_require hello.pm;

    perl_set $msie6 '

        sub {
            my $r = shift;
            my $ua = $r->header_in("User-Agent");

            return "" if $ua =~ /Opera/;
            return "1" if $ua =~ / MSIE [6-9]\.\d+/;
            return "";
        }

    ';

    server {
        location / {
            perl hello::handler;
        }
    }

The perl/lib/hello.pm module:

package hello;

use nginx;

sub handler {
    my $r = shift;

    $r->send_http_header("text/html");
    return OK if $r->header_only;

    $r->print("hello!\n<br/>");

    if (-f $r->filename or -d _) {
        $r->print($r->uri, " exists!\n");
    }

    return OK;
}

1;
__END__

Directives

            Syntax:

            perl module::function|'sub { ... }';

            Default:

            —

            Context:

            location, limit_except

Sets a Perl handler for the given location.

            Syntax:

            perl_modules path;

            Default:

            —

            Context:

            http

Sets an additional path for Perl modules.

            Syntax:

            perl_require module;

            Default:

            —

            Context:

            http

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

            Syntax:

            perl_set
    $variable
    module::function|'sub { ... }';

            Default:

            —

            Context:

            http

Installs a Perl handler for the specified variable.

Calling Perl from SSI

An SSI command calling Perl has the following format:

<!--# perl sub="module::function" arg="parameter1" arg="parameter2" ...
-->

The $r Request Object Methods

$r->args

returns request arguments.

$r->filename

returns a filename corresponding to the request URI.

    $r->has_request_body(handler)

returns 0 if there is no body in a request.
If there is a body, the specified handler is set for the request
and 1 is returned.
After reading the request body, nginx will call the specified handler.
Note that the handler function should be passed by reference.
Example:

package hello;

use nginx;

sub handler {
    my $r = shift;

    if ($r->request_method ne "POST") {
        return DECLINED;
    }

    if ($r->has_request_body(\&post)) {
        return OK;
    }

    return HTTP_BAD_REQUEST;
}

sub post {
    my $r = shift;

    $r->send_http_header;

    $r->print("request_body: \"", $r->request_body, "\"<br/>");
    $r->print("request_body_file: \"", $r->request_body_file, "\"<br/>\n");

    return OK;
}

1;

__END__

$r->allow_ranges

enables the use of byte ranges when sending responses.

$r->discard_request_body

instructs nginx to discard the request body.

$r->header_in(field)

returns the value of the specified client request header field.

$r->header_only

determines whether the whole response or only its header should be sent to
the client.

    $r->header_out(field,
    value)

sets a value for the specified response header field.

    $r->internal_redirect(uri)

does an internal redirect to the specified uri.
An actual redirect happens after the Perl handler execution is completed.

Since version 1.17.2, the method accepts escaped URIs and
supports redirections to named locations.

$r->log_error(errno,
message)

writes the specified message into the
error_log.
If errno is non-zero, an error code and its description
will be appended to the message.

$r->print(text, ...)

passes data to a client.

$r->request_body

returns the client request body if it has not been
written to a temporary file.
To ensure that the client request body is in memory,
its size should be limited by
client_max_body_size,
and a sufficient buffer size should be set using
client_body_buffer_size.

$r->request_body_file

returns the name of the file with the client request body.
After the processing, the file should be removed.
To always write a request body to a file,
client_body_in_file_only
should be enabled.

$r->request_method

returns the client request HTTP method.

$r->remote_addr

returns the client IP address.

$r->flush

immediately sends data to the client.

    $r->sendfile(name[,
    offset[,
    length]])

sends the specified file content to the client.
Optional parameters
specify the initial offset and length of the data to be transmitted.
The actual data transmission happens after the Perl handler
has completed.

    $r->send_http_header([type])

sends the response header to the client.
The optional type parameter sets the value of
the “Content-Type” response header field.
If the value is an empty string, the “Content-Type”
header field will not be sent.

$r->status(code)

sets a response code.

    $r->sleep(milliseconds,
    handler)

sets the specified handler
and stops request processing for the specified time.
In the meantime, nginx continues to process other requests.
After the specified time has elapsed, nginx will call the installed handler.
Note that the handler function should be passed by reference.
In order to pass data between handlers,
$r->variable() should be used.
Example:

package hello;

use nginx;

sub handler {
    my $r = shift;

    $r->discard_request_body;
    $r->variable("var", "OK");
    $r->sleep(1000, \&next);

    return OK;
}

sub next {
    my $r = shift;

    $r->send_http_header;
    $r->print($r->variable("var"));

    return OK;
}

1;

__END__

$r->unescape(text)

decodes a text encoded in the “%XX” form.

$r->uri

returns a request URI.

    $r->variable(name[,
    value])

returns or sets the value of the specified variable.
Variables are local to each request.