<!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>Security</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

Security

All nginx security issues should be reported to
F5SIRT@f5.com
or via one of the methods listed
here.

Patches are signed using one of the
PGP public keys.

Special considerations

njs does not evaluate dynamic code,
especially code received from the network, in any way.
The only way to evaluate that code using njs
is to configure the
js_import
directive in nginx.
JavaScript code is loaded once during nginx start.

In the nginx/njs threat model, JavaScript code is considered a trusted source
in the same way as nginx.conf and sites certificates.
What this means in practice:

memory disclosure and other security issues
triggered by JavaScript code modification
are not considered security vulnerabilities, but rather ordinary bugs

measures should be taken for protecting JavaScript code used by njs

if no js_import
directives are present in nginx.conf,
nginx is safe from JavaScript-related vulnerabilities

Advisories

Heap buffer overflow in js_fetch_proxy
Severity: medium
Advisory
CVE-2026-8711
Not vulnerable: 0.9.9+
Vulnerable: 0.9.4-0.9.8


<!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>Writing njs code using TypeScript definition files</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

Writing njs code using TypeScript definition files

Compiling TypeScript definition files
API checks and autocompletions
Writing njs type-safe code

TypeScript is
a typed superset of JavaScript
that compiles to plain JavaScript.

TypeScript supports definition files that contain
type information of existing JavaScript libraries.
This enables other programs to use the values defined in the files
as if they were statically typed TypeScript entities.

njs provides TypeScript definition files for its
API which can be used to:

Get autocompletion and API check in an editor

Write njs type-safe code

Compiling TypeScript definition files

$ git clone https://github.com/nginx/njs
$ cd njs && ./configure && make ts
$ ls build/ts/
njs_core.d.ts
njs_shell.d.ts
ngx_http_js_module.d.ts
ngx_stream_js_module.d.ts

API checks and autocompletions

Put *.d.ts files to a place where you editor can find it.

test.js:

/// <reference path="ngx_http_js_module.d.ts" />
/**
 * @param {NginxHTTPRequest} r
 * */
function content_handler(r) {
    r.headersOut['content-type'] = 'text/plain';
    r.return(200, "Hello");
}

Writing njs type-safe code

test.ts:

/// <reference path="ngx_http_js_module.d.ts" />
function content_handler(r: NginxHTTPRequest) {
    r.headersOut['content-type'] = 'text/plain';
    r.return(200, "Hello from TypeScript");
}

TypeScript installation:

# npm install -g typescript

TypeScript compilation:

$ tsc test.ts
$ cat test.js

The resulting test.js file can be used directly with njs.


<!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_stream_access_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_stream_access_module

Example Configuration
Directives
     allow
     deny

The ngx_stream_access_module module (1.9.2) allows
limiting access to certain client addresses.

Example Configuration

server {
    ...
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

The rules are checked in sequence until the first match is found.
In this example, access is allowed only for IPv4 networks
10.1.1.0/16 and 192.168.1.0/24
excluding the address 192.168.1.1,
and for IPv6 network 2001:0db8::/32.

Directives

            Syntax:

            allow
    address |
    CIDR |
    unix: |
    all;

            Default:

            —

            Context:

            stream, server

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

            Syntax:

            deny
    address |
    CIDR |
    unix: |
    all;

            Default:

            —

            Context:

            stream, server

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


<!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_stream_core_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_stream_core_module

Example Configuration
Directives
     listen
     preread_buffer_size
     preread_timeout
     proxy_protocol_timeout
     resolver
     resolver_timeout
     server
     server_name
     server_names_hash_bucket_size
     server_names_hash_max_size
     stream
     tcp_nodelay
     variables_hash_bucket_size
     variables_hash_max_size
Embedded Variables

The ngx_stream_core_module module
is available since version 1.9.0.
This module is not built by default, it should be enabled with the
--with-stream
configuration parameter.

Example Configuration

worker_processes auto;

error_log /var/log/nginx/error.log info;

events {
    worker_connections  1024;
}

stream {
    upstream backend {
        hash $remote_addr consistent;

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

    upstream dns {
       server 192.168.0.1:53535;
       server dns.example.com:53;
    }

    server {
        listen 12345;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass backend;
    }

    server {
        listen 127.0.0.1:53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }

    server {
        listen [::1]:12345;
        proxy_pass unix:/tmp/stream.socket;
    }
}

Directives

            Syntax:

            listen
    address:port
    [default_server]
    [ssl]
    [udp]
    [proxy_protocol]
    [setfib=number]
    [fastopen=number]
    [backlog=number]
    [rcvbuf=size]
    [sndbuf=size]
    [accept_filter=filter]
    [deferred]
    [bind]
    [ipv6only=on|off]
    [reuseport]
    [multipath]
    [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

            Default:

            —

            Context:

            server

Sets the address and port for the socket
on which the server will accept connections.
It is possible to specify just the port.
The address can also be a hostname, for example:

listen 127.0.0.1:12345;
listen *:12345;
listen 12345;     # same as *:12345
listen localhost:12345;

IPv6 addresses are specified in square brackets:

listen [::1]:12345;
listen [::]:12345;

UNIX-domain sockets are specified with the “unix:”
prefix:

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

Port ranges (1.15.10) are specified with the
first and last port separated by a hyphen:

listen 127.0.0.1:12345-12399;
listen 12345-12399;

The default_server parameter, if present,
will cause the server to become the default server for the specified
address:port pair (1.25.5).
If none of the directives have the default_server
parameter then the first server with the
address:port pair will be
the default server for this pair.

The ssl parameter allows specifying that all
connections accepted on this port should work in SSL mode.

The udp parameter configures a listening socket
for working with datagrams (1.9.13).
In order to handle packets from the same address and port in the same session,
the reuseport parameter
should also be specified.

The proxy_protocol parameter (1.11.4)
allows specifying that all connections accepted on this port should use the
PROXY
protocol.

The PROXY protocol version 2 is supported since version 1.13.11.

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

setfib=number

this parameter (1.25.5) sets the associated routing table, FIB
(the SO_SETFIB option) for the listening socket.
This currently works only on FreeBSD.

fastopen=number

enables
“TCP Fast Open”
for the listening socket (1.21.0) and
limits
the maximum length for the queue of connections that have not yet completed
the three-way handshake.

Do not enable this feature unless the server can handle
receiving the

same SYN packet with data more than once.

backlog=number

sets the backlog parameter in the
listen() call that limits
the maximum length for the queue of pending connections (1.9.2).
By default,
backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS,
and to 511 on other platforms.

rcvbuf=size

sets the receive buffer size
(the SO_RCVBUF option) for the listening socket (1.11.13).

sndbuf=size

sets the send buffer size
(the SO_SNDBUF option) for the listening socket (1.11.13).

accept_filter=filter

sets the name of accept filter
(the SO_ACCEPTFILTER option) for the listening socket
that filters incoming connections before passing them to
accept() (1.25.5).
This works only on FreeBSD and NetBSD 5.0+.
Possible values are
dataready
and
httpready.

deferred

instructs to use a deferred accept()
(the TCP_DEFER_ACCEPT socket option) on Linux (1.25.5).

bind

this parameter instructs to make a separate bind()
call for a given address:port pair.
The fact is that if there are several listen directives with
the same port but different addresses, and one of the
listen directives listens on all addresses
for the given port (*:port), nginx will
bind() only to *:port.
It should be noted that the getsockname() system call will be
made in this case to determine the address that accepted the connection.
If the setfib,
fastopen,
backlog, rcvbuf,
sndbuf, accept_filter,
deferred, ipv6only,
reuseport, multipath,
or so_keepalive parameters
are used then for a given
address:port pair
a separate bind() call will always be made.

ipv6only=on|off

this parameter determines
(via the IPV6_V6ONLY socket option)
whether an IPv6 socket listening on a wildcard address [::]
will accept only IPv6 connections or both IPv6 and IPv4 connections.
This parameter is turned on by default.
It can only be set once on start.

reuseport

this parameter (1.9.1) instructs to create an individual listening socket
for each worker process
(using the
SO_REUSEPORT socket option on Linux 3.9+ and DragonFly BSD,
or SO_REUSEPORT_LB on FreeBSD 12+), allowing a kernel
to distribute incoming connections between worker processes.
This currently works only on Linux 3.9+, DragonFly BSD,
and FreeBSD 12+ (1.15.1).

Inappropriate use of this option may have its security
implications.

multipath

this parameter (1.29.7) configures the
Multipath TCP
protocol (IPPROTO_MPTCP) for the listening socket.
This currently works only on Linux 5.6+.

Adding or removing this parameter will also enable
the SO_REUSEPORT socket option, which may have its security
implications.

so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]

this parameter configures the “TCP keepalive” behavior
for the listening socket.
If this parameter is omitted then the operating system’s settings will be
in effect for the socket.
If it is set to the value “on”, the
SO_KEEPALIVE option is turned on for the socket.
If it is set to the value “off”, the
SO_KEEPALIVE option is turned off for the socket.
Some operating systems support setting of TCP keepalive parameters on
a per-socket basis using the TCP_KEEPIDLE,
TCP_KEEPINTVL, and TCP_KEEPCNT socket options.
On such systems
(currently, Linux, NetBSD, Dragonfly, FreeBSD, and macOS),
they can be configured
using the keepidle, keepintvl, and
keepcnt parameters.
One or two parameters may be omitted, in which case the system default setting
for the corresponding socket option will be in effect.
For example,

so_keepalive=30m::10

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

Before version 1.25.5, different servers must listen on different
address:port pairs.

            Syntax:

            preread_buffer_size size;

            Default:

preread_buffer_size 16k;

            Context:

            stream, server

This directive appeared in version 1.11.5.

Specifies a size of the
preread buffer.

            Syntax:

            preread_timeout timeout;

            Default:

preread_timeout 30s;

            Context:

            stream, server

This directive appeared in version 1.11.5.

Specifies a timeout of the
preread phase.

            Syntax:

            proxy_protocol_timeout timeout;

            Default:

proxy_protocol_timeout 30s;

            Context:

            stream, server

This directive appeared in version 1.11.4.

Specifies a timeout for
reading the PROXY protocol header to complete.
If no entire header is transmitted within this time,
the connection is closed.

            Syntax:

            resolver
    address ...
    [valid=time]
    [ipv4=on|off]
    [ipv6=on|off]
    [status_zone=zone];

            Default:

            —

            Context:

            stream, server

This directive appeared in version 1.11.3.

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

resolver 127.0.0.1 [::1]:5353;

The address can be specified as a domain name or IP address,
with an optional port.
If port is not specified, the port 53 is used.
Name servers are queried in a round-robin fashion.

By default, nginx will look up both IPv4 and IPv6 addresses while resolving.
If looking up of IPv4 or IPv6 addresses is not desired,
the ipv4=off (1.23.1) or
the ipv6=off parameter can be specified.

By default, nginx caches answers using the TTL value of a response.
The optional valid parameter allows overriding it:

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

To prevent DNS spoofing, it is recommended
configuring DNS servers in a properly secured trusted local network.

The optional status_zone parameter (1.17.1)
enables
collection
of DNS server statistics of requests and responses
in the specified zone.
The parameter is available as part of our
commercial subscription.

Before version 1.11.3, this directive was available as part of our
commercial subscription.

            Syntax:

            resolver_timeout time;

            Default:

resolver_timeout 30s;

            Context:

            stream, server

This directive appeared in version 1.11.3.

Sets a timeout for name resolution, for example:

resolver_timeout 5s;

Before version 1.11.3, this directive was available as part of our
commercial subscription.

            Syntax:

            server { ... }

            Default:

            —

            Context:

            stream

Sets the configuration for a virtual server.
There is no clear separation between IP-based (based on the IP address)
and name-based (based on the
TLS
Server Name Indication extension (SNI, RFC 6066)) (1.25.5)
virtual servers.
Instead, the listen directives describe all
addresses and ports that should accept connections for the server, and the
server_name directive lists all server names.

            Syntax:

            server_name name ...;

            Default:

server_name "";

            Context:

            server

This directive appeared in version 1.25.5.

Sets names of a virtual server, for example:

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

The first name becomes the primary server name.

Server names can include an asterisk (“*”)
replacing the first or last part of a name:

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

Such names are called wildcard names.

The first two of the names mentioned above can be combined in one:

server {
    server_name .example.com;
}

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

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

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

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

    proxy_pass www.$2:12345;
}

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

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

    proxy_pass www.$domain:12345;
}

If the directive’s parameter is set to “$hostname”, the
machine’s hostname is inserted.

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

the exact name

the longest wildcard name starting with an asterisk,
e.g. “*.example.com”

the longest wildcard name ending with an asterisk,
e.g. “mail.*”

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

            Syntax:

            server_names_hash_bucket_size size;

            Default:

server_names_hash_bucket_size 32|64|128;

            Context:

            stream

This directive appeared in version 1.25.5.

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

            Syntax:

            server_names_hash_max_size size;

            Default:

server_names_hash_max_size 512;

            Context:

            stream

This directive appeared in version 1.25.5.

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

            Syntax:

            stream { ... }

            Default:

            —

            Context:

            main

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

            Syntax:

            tcp_nodelay on | off;

            Default:

tcp_nodelay on;

            Context:

            stream, server

This directive appeared in version 1.9.4.

Enables or disables the use of the TCP_NODELAY option.
The option is enabled for both client and proxied server connections.

            Syntax:

            variables_hash_bucket_size size;

            Default:

variables_hash_bucket_size 64;

            Context:

            stream

This directive appeared in version 1.11.2.

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

            Syntax:

            variables_hash_max_size size;

            Default:

variables_hash_max_size 1024;

            Context:

            stream

This directive appeared in version 1.11.2.

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

Embedded Variables

The ngx_stream_core_module module supports variables
since 1.11.2.

$binary_remote_addr

client address in a binary form, value’s length is always 4 bytes
for IPv4 addresses or 16 bytes for IPv6 addresses

$bytes_received

number of bytes received from a client (1.11.4)

$bytes_sent

number of bytes sent to a client

$connection

connection serial number

$hostname

host name

$msec

current time in seconds with the milliseconds resolution

$nginx_version

nginx version

$pid

PID of the worker process

$protocol

protocol used to communicate with the client:
TCP or UDP (1.11.4)

$proxy_protocol_addr

client address from the PROXY protocol header (1.11.4)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_port

client port from the PROXY protocol header (1.11.4)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_server_addr

server address from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_server_port

server port from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_tlv_name

TLV from the PROXY Protocol header (1.23.2).
The name can be a TLV type name or its numeric value.
In the latter case, the value is hexadecimal
and should be prefixed with 0x:

$proxy_protocol_tlv_alpn
$proxy_protocol_tlv_0x01

SSL TLVs can also be accessed by TLV type name or its numeric value,
both prefixed by ssl_:

$proxy_protocol_tlv_ssl_version
$proxy_protocol_tlv_ssl_0x21

The following TLV type names are supported:

alpn (0x01) -
upper layer protocol used over the connection

authority (0x02) -
host name value passed by the client

unique_id (0x05) -
unique connection id

netns (0x30) -
name of the namespace

ssl (0x20) -
binary SSL TLV structure

The following SSL TLV type names are supported:

ssl_version (0x21) -
SSL version used in client connection

ssl_cn (0x22) -
SSL certificate Common Name

ssl_cipher (0x23) -
name of the used cipher

ssl_sig_alg (0x24) -
algorithm used to sign the certificate

ssl_key_alg (0x25) -
public-key algorithm

Also, the following special SSL TLV type name is supported:

ssl_verify -
client SSL certificate verification result,
zero if the client presented a certificate
and it was successfully verified, and non-zero otherwise

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$remote_addr

client address

$remote_port

client port

$server_addr

an address of the server which accepted a connection

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

$server_port

port of the server which accepted a connection

$session_time

session duration in seconds with a milliseconds resolution
(1.11.4);

$status

session status (1.11.4), can be one of the following:

200

session completed successfully

400

client data could not be parsed, for example,
the PROXY protocol header

403

access forbidden, for example, when access is limited for
certain client addresses

500

internal server error

502

bad gateway, for example,
if an upstream server could not be selected or reached.

503

service unavailable, for example, when access is limited by the
number of connections

$time_iso8601

local time in the ISO 8601 standard format

$time_iso8601_ms

local time in the ISO 8601 standard format
with a millisecond resolution (1.29.8)

This variable is available as part of our
commercial subscription.

$time_local

local time in the Common Log Format


<!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_stream_geoip_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_stream_geoip_module

Example Configuration
Directives
     geoip_country
     geoip_city
     geoip_org

The ngx_stream_geoip_module module (1.11.3) creates variables
with values depending on the client IP address, using the precompiled
MaxMind databases.

When using the databases with IPv6 support,
IPv4 addresses are looked up as IPv4-mapped IPv6 addresses.

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

This module requires the
MaxMind GeoIP library.

Example Configuration

stream {
    geoip_country         GeoIP.dat;
    geoip_city            GeoLiteCity.dat;

    map $geoip_city_continent_code $nearest_server {
        default        example.com;
        EU          eu.example.com;
        NA          na.example.com;
        AS          as.example.com;
    }
   ...
}

Directives

            Syntax:

            geoip_country file;

            Default:

            —

            Context:

            stream

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

$geoip_country_code

two-letter country code, for example,
“RU”, “US”.

$geoip_country_code3

three-letter country code, for example,
“RUS”, “USA”.

$geoip_country_name

country name, for example,
“Russian Federation”, “United States”.

            Syntax:

            geoip_city file;

            Default:

            —

            Context:

            stream

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

$geoip_area_code

telephone area code (US only).

This variable may contain outdated information since
the corresponding database field is deprecated.

$geoip_city_continent_code

two-letter continent code, for example,
“EU”, “NA”.

$geoip_city_country_code

two-letter country code, for example,
“RU”, “US”.

$geoip_city_country_code3

three-letter country code, for example,
“RUS”, “USA”.

$geoip_city_country_name

country name, for example,
“Russian Federation”, “United States”.

$geoip_dma_code

DMA region code in US (also known as “metro code”), according to the
geotargeting
in Google AdWords API.

$geoip_latitude

latitude.

$geoip_longitude

longitude.

$geoip_region

two-symbol country region code (region, territory, state, province, federal land
and the like), for example,
“48”, “DC”.

$geoip_region_name

country region name (region, territory, state, province, federal land
and the like), for example,
“Moscow City”, “District of Columbia”.

$geoip_city

city name, for example,
“Moscow”, “Washington”.

$geoip_postal_code

postal code.

            Syntax:

            geoip_org file;

            Default:

            —

            Context:

            stream

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

$geoip_org

organization name, for example, “The University of Melbourne”.


<!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_stream_geo_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_stream_geo_module

Example Configuration
Directives
     geo

The ngx_stream_geo_module module (1.11.3) creates variables
with values depending on the client IP address.

Example Configuration

geo $geo {
    default        0;

    127.0.0.1      2;
    192.168.1.0/24 1;
    10.1.0.0/16    1;

    ::1            2;
    2001:0db8::/32 1;
}

Directives

            Syntax:

            geo [$address] $variable { ... }

            Default:

            —

            Context:

            stream

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

geo $arg_remote_addr $geo {
    ...;
}

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

If the value of a variable does not represent a valid IP address
then the “255.255.255.255” address is used.

Addresses are specified either as prefixes in CIDR notation
(including individual addresses) or as ranges.

The following special parameters are also supported:

delete

deletes the specified network.

default

a value set to the variable if the client address does not
match any of the specified addresses.
When addresses are specified in CIDR notation,
“0.0.0.0/0” and “::/0”
can be used instead of default.
When default is not specified, the default
value will be an empty string.

include

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

ranges

indicates that addresses are specified as ranges.
This parameter should be the first.
To speed up loading of a geo base, addresses should be put in ascending order.

volatile

indicates that the variable is not cacheable (1.29.3).

Example:

geo $country {
    default        ZZ;
    include        conf/geo.conf;
    delete         127.0.0.0/16;

    127.0.0.0/24   US;
    127.0.0.1/32   RU;
    10.1.0.0/16    RU;
    192.168.1.0/24 UK;
}

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

10.2.0.0/16    RU;
192.168.2.0/24 RU;

A value of the most specific match is used.
For example, for the 127.0.0.1 address the value “RU”
will be chosen, not “US”.

Example with ranges:

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


<!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_stream_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_stream_js_module

Example Configuration
Directives
     js_access
     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_filter
     js_import
     js_include
     js_load_stream_native_module
     js_path
     js_periodic
     js_preload_object
     js_preread
     js_set
     js_shared_dict_zone
     js_var
Session Object Properties

The ngx_stream_js_module module is used to implement
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.

stream {
    js_import stream.js;

    js_set $bar stream.bar;
    js_set $req_line stream.req_line;

    server {
        listen 12345;

        js_preread stream.preread;
        return     $req_line;
    }

    server {
        listen 12346;

        js_access  stream.access;
        proxy_pass 127.0.0.1:8000;
        js_filter  stream.header_inject;
    }
}

http {
    server {
        listen 8000;
        location / {
            return 200 $http_foo\n;
        }
    }
}

The stream.js file:

var line = '';

function bar(s) {
    var v = s.variables;
    s.log("hello from bar() handler!");
    return "bar-var" + v.remote_port + "; pid=" + v.pid;
}

function preread(s) {
    s.on('upload', function (data, flags) {
        var n = data.indexOf('\n');
        if (n != -1) {
            line = data.substr(0, n);
            s.done();
        }
    });
}

function req_line(s) {
    return line;
}

// Read HTTP request line.
// Collect bytes in 'req' until
// request line is read.
// Injects HTTP header into a client's request

var my_header =  'Foo: foo';
function header_inject(s) {
    var req = '';
    s.on('upload', function(data, flags) {
        req += data;
        var n = req.search('\n');
        if (n != -1) {
            var rest = req.substr(n + 1);
            req = req.substr(0, n + 1);
            s.send(req + my_header + '\r\n' + rest, flags);
            s.off('upload');
        }
    });
}

function access(s) {
    if (s.remoteAddress.match('^192.*')) {
        s.deny();
        return;
    }

    s.allow();
}

export default {bar, preread, req_line, header_inject, access};

Directives

            Syntax:

            js_access module.function;

            Default:

            —

            Context:

            stream, server

Sets an njs function which will be called at the
access phase.
Since 0.4.0,
a module function can be referenced.

The function is called once at the moment when the stream session reaches
the access phase
for the first time.
The function is called with the following arguments:

s

the Stream Session object

At this phase, it is possible to perform initialization
or register a callback with
the s.on()
method
for each incoming data chunk until one of the following methods are called:
s.allow(),
s.decline(),
s.done().
As soon as one of these methods is called, the stream session processing
switches to the next phase
and all current
s.on()
callbacks are dropped.

            Syntax:

            js_context_reuse number;

            Default:

js_context_reuse 128;

            Context:

            stream, server

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 stream session.
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:

            stream, server

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:

            stream, server

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:

            stream, server

This directive appeared in version 0.7.0.

Specifies the enabled ciphers for HTTPS connections
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:

            stream, server

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:

            stream, server

This directive appeared in version 0.7.0.

Enables the specified protocols for HTTPS connections
with Fetch API.

            Syntax:

            js_fetch_timeout time;

            Default:

js_fetch_timeout 60s;

            Context:

            stream, server

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:

            stream, server

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:

            stream, server

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:

            stream, server

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:

            stream, server

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:

server {
    listen 12345;
    js_fetch_proxy http://user:pass@proxy.example.com:3128;
    js_preread main.fetch_handler;
}

            Syntax:

            js_fetch_keepalive connections;

            Default:

js_fetch_keepalive 0;

            Context:

            stream, server

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:

server {
    listen 12345;
    js_fetch_keepalive 32;
    js_fetch_trusted_certificate /path/to/ISRG_Root_X1.pem;
    js_preread main.fetch_handler;
}

            Syntax:

            js_fetch_keepalive_requests number;

            Default:

js_fetch_keepalive_requests 1000;

            Context:

            stream, server

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:

            stream, server

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:

            stream, server

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_filter module.function;

            Default:

            —

            Context:

            stream, server

Sets a data filter.
Since 0.4.0,
a module function can be referenced.
The filter function is called once at the moment when the stream session reaches
the content phase.

The filter function is called with the following arguments:

s

the Stream Session object

At this phase, it is possible to perform initialization
or register a callback with
the s.on()
method for each incoming data chunk.
The
s.off()
method may be used to unregister a callback and stop filtering.

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

            Syntax:

            js_import module.js |
export_name from module.js;

            Default:

            —

            Context:

            stream, server

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 stream.js;

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

Several js_import directives can be specified.

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

            Syntax:

            js_include file;

            Default:

            —

            Context:

            stream

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

nginx.conf:
js_include stream.js;
js_set     $js_addr address;
server {
    listen 127.0.0.1:12345;
    return $js_addr;
}

stream.js:
function address(s) {
    return s.remoteAddress;
}

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_stream_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 Stream 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_stream_native_module /path/to/mylib.so;
js_load_stream_native_module /path/to/other.so as myalias;

stream {
    js_import main.js;
    # ... rest of stream 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:

            stream, server

This directive appeared in version 0.3.0.

Sets an additional path for njs modules.

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

            Syntax:

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

            Default:

            —

            Context:

            server

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:

            stream, server

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_preread module.function;

            Default:

            —

            Context:

            stream, server

Sets an njs function which will be called at the
preread phase.
Since 0.4.0,
a module function can be referenced.

The function is called once
at the moment when the stream session reaches the
preread phase
for the first time.
The function is called with the following arguments:

s

the Stream Session object

At this phase, it is possible to perform initialization
or register a callback with
the s.on()
method
for each incoming data chunk until one of the following methods are called:
s.allow(),
s.decline(),
s.done().
When one of these methods is called,
the stream session switches to the
next phase
and all current
s.on()
callbacks are dropped.

As the js_preread handler
returns its result immediately, it supports
only synchronous callbacks.
Thus, asynchronous callbacks such as
ngx.fetch()
or
setTimeout()
are not supported.
Nevertheless, asynchronous operations are supported in
s.on()
callbacks in the
preread phase.
See
this example for more information.

            Syntax:

            js_set
    $variable
    module.function
    [nocache];

            Default:

            —

            Context:

            stream, server

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, when
optional argument nocache is provided 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 callbacks.
Thus, asynchronous callbacks such as
ngx.fetch()
or
setTimeout()
are not supported.

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

            Syntax:

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

            Default:

            —

            Context:

            stream

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:

            stream, server

This directive appeared in version 0.5.3.

Declares
a writable
variable.
The value can contain text, variables, and their combination.

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

Session Object Properties

Each stream njs handler receives one argument, a stream session
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_stream_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_stream_keyval_module

Example Configuration
Directives
     keyval
     keyval_zone

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

This module is available as part of our
commercial subscription.

Example Configuration

http {

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

stream {

    keyval_zone zone=one:32k state=/var/lib/nginx/state/one.keyval;
    keyval      $ssl_server_name $name zone=one;

    server {
        listen              12345 ssl;
        proxy_pass          $name;
        ssl_certificate     /usr/local/nginx/conf/cert.pem;
        ssl_certificate_key /usr/local/nginx/conf/cert.key;
    }
}

Directives

            Syntax:

            keyval
    key
    $variable
    zone=name;

            Default:

            —

            Context:

            stream

Creates a new $variable whose value
is looked up by the key in the key-value database.
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:

            stream

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

The optional state parameter specifies a file
that keeps the current state of the key-value database in the JSON format
and makes it persistent across nginx restarts.
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_stream_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_stream_limit_conn_module

Example Configuration
Directives
     limit_conn
     limit_conn_dry_run
     limit_conn_log_level
     limit_conn_zone
Embedded Variables

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

Example Configuration

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

    ...

    server {

        ...

        limit_conn           addr 1;
        limit_conn_log_level error;
    }
}

Directives

            Syntax:

            limit_conn zone number;

            Default:

            —

            Context:

            stream, server

Sets the shared memory zone
and the maximum allowed number of connections for a given key value.
When this limit is exceeded, the server will close the connection.
For example, the directives

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    ...
    limit_conn addr 1;
}

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

When several limit_conn directives are specified,
any configured limit will apply.

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:

            stream, server

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:

            stream, server

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

            Syntax:

            limit_conn_zone
    key
    zone=name:size;

            Default:

            —

            Context:

            stream

Sets parameters for a shared memory zone
that will keep states for various keys.
In particular, the state includes the current number of connections.
The key can contain text, variables,
and their combinations (1.11.2).
Connections with an empty key value are not accounted.
Usage example:

limit_conn_zone $binary_remote_addr zone=addr:10m;

Here, the key is a client IP address set by the
$binary_remote_addr variable.
The size of $binary_remote_addr
is 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 close the connection.

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_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_stream_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_stream_log_module

Example Configuration
Directives
     access_log
     log_format
     open_log_file_cache

The ngx_stream_log_module module (1.11.4) writes session logs
in the specified format.

Example Configuration

log_format basic '$remote_addr [$time_local] '
                 '$protocol $status $bytes_sent $bytes_received '
                 '$session_time';

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

Directives

            Syntax:

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

            Default:

access_log off;

            Context:

            stream, server

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 either the buffer or gzip
parameter is used, writes to log will be buffered.

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

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;

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 basic gzip flush=5m;

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

The file path can contain variables,
but such logs have some constraints:

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

buffered writes do not work;

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

The if parameter enables conditional logging.
A session will not be logged if the condition evaluates to “0”
or an empty string.

            Syntax:

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

            Default:

            —

            Context:

            stream

Specifies the log format, for example:

log_format proxy '$remote_addr [$time_local] '
                 '$protocol $status $bytes_sent $bytes_received '
                 '$session_time "$upstream_addr" '
                 '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

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

For default escaping,
characters “"”, “\”,
and other characters with values less than 32 or above 126
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”.

            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:

            stream, server

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_stream_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_stream_map_module

Example Configuration
Directives
     map
     map_hash_bucket_size
     map_hash_max_size

The ngx_stream_map_module module (1.11.2) creates variables
whose values depend on values of other variables.

Example Configuration

map $remote_addr $limit {
    127.0.0.1    "";
    default      $binary_remote_addr;
}

limit_conn_zone $limit zone=addr:10m;
limit_conn addr 1;

Directives

            Syntax:

            map
    string
    $variable { ... }

            Default:

            —

            Context:

            stream

Creates a new variable whose value
depends on values of one or more of the source variables
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 connection processing.

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

Source values are specified as strings or regular expressions.

Strings are matched ignoring the case.

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

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, and their combination.

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:

            stream

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:

            stream

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_stream_mqtt_filter_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_stream_mqtt_filter_module

Example Configuration
Directives
     mqtt
     mqtt_buffers
     mqtt_rewrite_buffer_size
     mqtt_set_connect

The ngx_stream_mqtt_filter_module module (1.23.4) provides
support for Message Queuing Telemetry Transport protocol (MQTT) versions
3.1.1
and
5.0.

This module is available as part of our
commercial subscription.

Example Configuration

listen            127.0.0.1:18883;
proxy_pass        backend;
proxy_buffer_size 16k;

mqtt             on;
mqtt_set_connect clientid "$client";
mqtt_set_connect username "$name";

Directives

            Syntax:

            mqtt on | off;

            Default:

mqtt off;

            Context:

            stream, server

Enables the MQTT protocol for the given virtual server.

            Syntax:

            mqtt_buffers number size;

            Default:

mqtt_buffers 100 1k;

            Context:

            stream, server

This directive appeared in version 1.25.1.

Sets the number and size of the buffers
used for handling MQTT messages,
for a single connection.

            Syntax:

            mqtt_rewrite_buffer_size size;

            Default:

mqtt_rewrite_buffer_size 4k|8k;

            Context:

            server

This directive is obsolete since version 1.25.1.
The mqtt_buffers
directive should be used instead.

Sets the size of the buffer
used for writing a modified message.
By default, the buffer size is equal to one memory page.
This is either 4K or 8K, depending on a platform.
It can be made smaller, however.

            Syntax:

            mqtt_set_connect field value;

            Default:

            —

            Context:

            server

Sets the message field
to the given value for CONNECT message.
The following fields are supported:
clientid,
username, and
password.
The value can contain text, variables, and their combination.

Several mqtt_set_connect directives
can be specified on the same level:

mqtt_set_connect clientid "$client";
mqtt_set_connect username "$name";


<!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_stream_mqtt_preread_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_stream_mqtt_preread_module

Example Configuration
Directives
     mqtt_preread
Embedded Variables

The ngx_stream_mqtt_preread_module module (1.23.4) allows
extracting information from the CONNECT message
of the Message Queuing Telemetry Transport protocol (MQTT) versions
3.1.1
and
5.0,
for example, a username or a client ID.

This module is available as part of our
commercial subscription.

Example Configuration

mqtt_preread on;
return       $mqtt_preread_clientid;

Directives

            Syntax:

            mqtt_preread on | off;

            Default:

mqtt_preread off;

            Context:

            stream, server

Enables extracting information from the MQTT CONNECT message at
the preread phase.

Embedded Variables

$mqtt_preread_clientid

the clientid value from the CONNECT message

$mqtt_preread_username

the username value from the CONNECT message


<!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_stream_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_stream_num_map_module

Example Configuration
Directives
     num_map

The ngx_stream_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:

            stream

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 connection 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_stream_pass_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_stream_pass_module

Example Configuration
Directives
     pass

The ngx_stream_pass_module module (1.25.5) allows
passing the accepted connection directly to any configured listening socket
in http, stream, mail,
and other similar modules.

Example Configuration

http {
    server {
        listen 8000;

        location / {
            root html;
        }
    }
}

stream {
    server {
        listen 12345 ssl;

        ssl_certificate     domain.crt;
        ssl_certificate_key domain.key;

        pass 127.0.0.1:8000;
    }
}

In the example,
after terminating SSL/TLS in the stream module
the connection is passed to the http module.

Directives

            Syntax:

            pass address;

            Default:

            —

            Context:

            server

Sets server address to pass client connection to.
The address can be specified as an IP address
and a port:

pass 127.0.0.1:12345;

or as a UNIX-domain socket path:

pass unix:/tmp/stream.socket;

The address can also be specified using variables:

pass $upstream;


<!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_stream_proxy_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_stream_proxy_module

Example Configuration
Directives
     proxy_bind
     proxy_bind_dynamic
     proxy_buffer_size
     proxy_connect_timeout
     proxy_download_rate
     proxy_half_close
     proxy_next_upstream
     proxy_next_upstream_timeout
     proxy_next_upstream_tries
     proxy_pass
     proxy_protocol
     proxy_requests
     proxy_responses
     proxy_session_drop
     proxy_socket_keepalive
     proxy_ssl
     proxy_ssl_alpn
     proxy_ssl_certificate
     proxy_ssl_certificate_cache
     proxy_ssl_certificate_key
     proxy_ssl_ciphers
     proxy_ssl_conf_command
     proxy_ssl_crl
     proxy_ssl_key_log
     proxy_ssl_name
     proxy_ssl_password_file
     proxy_ssl_protocols
     proxy_ssl_server_name
     proxy_ssl_session_reuse
     proxy_ssl_trusted_certificate
     proxy_ssl_verify
     proxy_ssl_verify_depth
     proxy_timeout
     proxy_upload_rate

The ngx_stream_proxy_module module (1.9.0) allows proxying
data streams over TCP, UDP (1.9.13), and UNIX-domain sockets.

Example Configuration

server {
    listen 127.0.0.1:12345;
    proxy_pass 127.0.0.1:8080;
}

server {
    listen 12345;
    proxy_connect_timeout 1s;
    proxy_timeout 1m;
    proxy_pass example.com:12345;
}

server {
    listen 53 udp reuseport;
    proxy_timeout 20s;
    proxy_pass dns.example.com:53;
}

server {
    listen [::1]:12345;
    proxy_pass unix:/tmp/stream.socket;
}

Directives

            Syntax:

            proxy_bind
    address
    [transparent] |
    off;

            Default:

            —

            Context:

            stream, server

This directive appeared in version 1.9.2.

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

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

proxy_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 proxied server.

            Syntax:

            proxy_bind_dynamic on | off;

            Default:

proxy_bind_dynamic off;

            Context:

            stream, server

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:

            proxy_buffer_size size;

            Default:

proxy_buffer_size 16k;

            Context:

            stream, server

This directive appeared in version 1.9.4.

Sets the size of the buffer used for reading data
from the proxied server.
Also sets the size of the buffer used for reading data
from the client.

            Syntax:

            proxy_connect_timeout time;

            Default:

proxy_connect_timeout 60s;

            Context:

            stream, server

Defines a timeout for establishing a connection with a proxied server.

            Syntax:

            proxy_download_rate rate;

            Default:

proxy_download_rate 0;

            Context:

            stream, server

This directive appeared in version 1.9.3.

Limits the speed of reading the data from the proxied server.
The rate is specified in bytes per second.
The zero value disables rate limiting.
The limit is set per a connection, so if nginx simultaneously opens
two connections to the proxied server,
the overall rate will be twice as much as the specified limit.

Parameter value can contain variables (1.17.0).
It may be useful in cases where rate should be limited
depending on a certain condition:

map $slow $rate {
    1     4k;
    2     8k;
}

proxy_download_rate $rate;

            Syntax:

            proxy_half_close on | off;

            Default:

proxy_half_close off;

            Context:

            stream, server

This directive appeared in version 1.21.4.

Enables or disables closing
each direction of a TCP connection independently (“TCP half-close”).
If enabled, proxying over TCP will be kept
until both sides close the connection.

            Syntax:

            proxy_next_upstream on | off;

            Default:

proxy_next_upstream on;

            Context:

            stream, server

When a connection to the proxied server cannot be established, determines
whether a client connection will be passed to the next server.

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

            Syntax:

            proxy_next_upstream_timeout time;

            Default:

proxy_next_upstream_timeout 0;

            Context:

            stream, server

Limits the time allowed to pass a connection to the
next server.
The 0 value turns off this limitation.

            Syntax:

            proxy_next_upstream_tries number;

            Default:

proxy_next_upstream_tries 0;

            Context:

            stream, server

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

            Syntax:

            proxy_pass address;

            Default:

            —

            Context:

            server

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

proxy_pass localhost:12345;

or as a UNIX-domain socket path:

proxy_pass unix:/tmp/stream.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.

The address can also be specified using variables (1.11.3):

proxy_pass $upstream;

In this case, the server name is searched among the described
server groups,
and, if not found, is determined using a
resolver.

            Syntax:

            proxy_protocol on | off;

            Default:

proxy_protocol off;

            Context:

            stream, server

This directive appeared in version 1.9.2.

Enables the
PROXY
protocol for connections to a proxied server.

            Syntax:

            proxy_requests number;

            Default:

proxy_requests 0;

            Context:

            stream, server

This directive appeared in version 1.15.7.

Sets the number of client datagrams at which
binding between a client and existing UDP stream session is dropped.
After receiving the specified number of datagrams, next datagram
from the same client starts a new session.
The session terminates when all client datagrams are transmitted
to a proxied server and the expected number of
responses is received,
or when it reaches a timeout.

            Syntax:

            proxy_responses number;

            Default:

            —

            Context:

            stream, server

This directive appeared in version 1.9.13.

Sets the number of datagrams expected from the proxied server
in response to a client datagram
if the UDP
protocol is used.
The number serves as a hint for session termination.
By default, the number of datagrams is not limited.

If zero value is specified, no response is expected.
However, if a response is received and the
session is still not finished, the response will be handled.

            Syntax:

            proxy_session_drop on | off;

            Default:

proxy_session_drop off;

            Context:

            stream, server

This directive appeared in version 1.15.8.

Enables terminating all sessions to a proxied server
after it was removed from the group or marked as permanently unavailable.
This can occur because of
re-resolve
or with the API
DELETE
command.
A server can be marked as permanently unavailable if it is considered
unhealthy
or with the API
PATCH
command.
Each session is terminated when the next
read or write event is processed for the client or proxied server.

This directive is available as part of our
commercial subscription.

            Syntax:

            proxy_socket_keepalive on | off;

            Default:

proxy_socket_keepalive off;

            Context:

            stream, server

This directive appeared in version 1.15.6.

Configures the “TCP keepalive” behavior
for outgoing connections to a proxied 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.

            Syntax:

            proxy_ssl on | off;

            Default:

proxy_ssl off;

            Context:

            stream, server

Enables the SSL/TLS protocol for connections to a proxied server.

            Syntax:

            proxy_ssl_alpn protocol ...;

            Default:

            —

            Context:

            stream, server

This directive appeared in version 1.31.0.

Specifies the list of protocols to advertise via the
ALPN
extension when establishing a connection with the proxied server.
For example:

proxy_ssl_alpn h2 http/1.1;

Parameter value can contain variables:

proxy_ssl_alpn $ssl_alpn_protocol;

            Syntax:

            proxy_ssl_certificate file;

            Default:

            —

            Context:

            stream, server

Specifies a file with the certificate in the PEM format
used for authentication to a proxied server.

Since version 1.21.0, variables can be used in the file name.

            Syntax:

            proxy_ssl_certificate_cache off;
proxy_ssl_certificate_cache
    max=N
    [inactive=time]
    [valid=time];

            Default:

proxy_ssl_certificate_cache off;

            Context:

            stream, server

This directive appeared in version 1.27.4.

Defines a cache that stores
SSL certificates and
secret keys
specified with variables.

The directive has the following parameters:

max

sets the maximum number of elements in the cache;
on cache overflow the least recently used (LRU) elements are removed;

inactive

defines a time after which an element is removed from the cache
if it has not been accessed during this time;
by default, it is 10 seconds;

valid

defines a time during which
an element in the cache is considered valid
and can be reused;
by default, it is 60 seconds.
Certificates that exceed this time will be reloaded or revalidated;

off

disables the cache.

Example:

proxy_ssl_certificate       $proxy_ssl_server_name.crt;
proxy_ssl_certificate_key   $proxy_ssl_server_name.key;
proxy_ssl_certificate_cache max=1000 inactive=20s valid=1m;

            Syntax:

            proxy_ssl_certificate_key file;

            Default:

            —

            Context:

            stream, server

The value
store:scheme:id
can be specified instead of the file (1.29.0),
which is used to load a secret key with a specified id
and OpenSSL provider registered URI scheme, such as
pkcs11.

Specifies a file with the secret key in the PEM format
used for authentication to a proxied server.

Since version 1.21.0, variables can be used in the file name.

            Syntax:

            proxy_ssl_ciphers ciphers;

            Default:

proxy_ssl_ciphers DEFAULT;

            Context:

            stream, server

Specifies the enabled ciphers for connections to a proxied server.
The ciphers are specified in the format understood by the OpenSSL library.

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

            Syntax:

            proxy_ssl_conf_command name value;

            Default:

            —

            Context:

            stream, server

This directive appeared in version 1.19.4.

Sets arbitrary OpenSSL configuration
commands
when establishing a connection with the proxied server.

The directive is supported when using OpenSSL 1.0.2 or higher.

Several proxy_ssl_conf_command directives
can be specified on the same level.
These directives are inherited from the previous configuration level
if and only if there are
no proxy_ssl_conf_command directives
defined on the current level.

Note that configuring OpenSSL directly
might result in unexpected behavior.

            Syntax:

            proxy_ssl_crl file;

            Default:

            —

            Context:

            stream, server

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

            Syntax:

            proxy_ssl_key_log path;

            Default:

            —

            Context:

            stream, server

This directive appeared in version 1.27.2.

Enables logging of proxied server connection SSL keys
and specifies the path to the key log file.
Keys are logged in the
SSLKEYLOGFILE
format compatible with Wireshark.

This directive is available as part of our
commercial subscription.

            Syntax:

            proxy_ssl_name name;

            Default:

proxy_ssl_name host from proxy_pass;

            Context:

            stream, server

Allows overriding the server name used to
verify
the certificate of the proxied server and to be
passed through SNI
when establishing a connection with the proxied server.
The server name can also be specified using variables (1.11.3).

By default, the host part of the proxy_pass address is used.

            Syntax:

            proxy_ssl_password_file file;

            Default:

            —

            Context:

            stream, server

Specifies a file with passphrases for
secret keys
where each passphrase is specified on a separate line.
Passphrases are tried in turn when loading the key.

            Syntax:

            proxy_ssl_protocols
    [SSLv2]
    [SSLv3]
    [TLSv1]
    [TLSv1.1]
    [TLSv1.2]
    [TLSv1.3];

            Default:

proxy_ssl_protocols TLSv1.2 TLSv1.3;

            Context:

            stream, server

Enables the specified protocols for connections to a proxied server.

The TLSv1.3 parameter is used by default
since 1.23.4.

            Syntax:

            proxy_ssl_server_name on | off;

            Default:

proxy_ssl_server_name off;

            Context:

            stream, server

Enables or disables passing of the server name through
TLS
Server Name Indication extension (SNI, RFC 6066)
when establishing a connection with the proxied server.

            Syntax:

            proxy_ssl_session_reuse on | off;

            Default:

proxy_ssl_session_reuse on;

            Context:

            stream, server

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

            Syntax:

            proxy_ssl_trusted_certificate file;

            Default:

            —

            Context:

            stream, server

Specifies a file with trusted CA certificates in the PEM format
used to verify
the certificate of the proxied server.

            Syntax:

            proxy_ssl_verify on | off;

            Default:

proxy_ssl_verify off;

            Context:

            stream, server

Enables or disables verification of the proxied server certificate.

            Syntax:

            proxy_ssl_verify_depth number;

            Default:

proxy_ssl_verify_depth 1;

            Context:

            stream, server

Sets the verification depth in the proxied server certificates chain.

            Syntax:

            proxy_timeout timeout;

            Default:

proxy_timeout 10m;

            Context:

            stream, server

Sets the timeout between two successive
read or write operations on client or proxied server connections.
If no data is transmitted within this time, the connection is closed.

            Syntax:

            proxy_upload_rate rate;

            Default:

proxy_upload_rate 0;

            Context:

            stream, server

This directive appeared in version 1.9.3.

Limits the speed of reading the data from the client.
The rate is specified in bytes per second.
The zero value disables rate limiting.
The limit is set per a connection, so if the client simultaneously opens
two connections,
the overall rate will be twice as much as the specified limit.

Parameter value can contain variables (1.17.0).
It may be useful in cases where rate should be limited
depending on a certain condition:

map $slow $rate {
    1     4k;
    2     8k;
}

proxy_upload_rate $rate;


<!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_stream_proxy_protocol_vendor_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_stream_proxy_protocol_vendor_module

Example Configuration
Embedded Variables

The ngx_stream_proxy_protocol_vendor_module module (1.23.3)
allows obtaining additional information about a connection in
cloud platforms from application-specific TLVs of the
PROXY
protocol
header.

Supported cloud platforms:

Amazon Web Services

Google Cloud Platform

Microsoft Azure

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

This module is available as part of our
commercial subscription.

Example Configuration

server {
    listen 12345 proxy_protocol;
    return $proxy_protocol_tlv_gcp_conn_id;
}

Embedded Variables

$proxy_protocol_tlv_aws_vpce_id

TLV value from the PROXY Protocol header representing the
ID
of AWS VPC endpoint

$proxy_protocol_tlv_azure_pel_id

TLV value from the PROXY Protocol header representing the
LinkID
of Azure private endpoint

$proxy_protocol_tlv_gcp_conn_id

TLV value from the PROXY Protocol header representing
Google Cloud PSC
connection ID


<!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_stream_realip_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_stream_realip_module

Example Configuration
Directives
     set_real_ip_from
Embedded Variables

The ngx_stream_realip_module module is used
to change the client address and port
to the ones sent in the PROXY protocol header (1.11.4).
The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

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

Example Configuration

listen 12345 proxy_protocol;

set_real_ip_from  192.168.1.0/24;
set_real_ip_from  192.168.2.1;
set_real_ip_from  2001:0db8::/32;

Directives

            Syntax:

            set_real_ip_from
    address |
    CIDR |
    unix:;

            Default:

            —

            Context:

            stream, server

Defines trusted addresses that are known to send correct
replacement addresses.
If the special value unix: is specified,
all UNIX-domain sockets will be trusted.

Embedded Variables

$realip_remote_addr

keeps the original client address

$realip_remote_port

keeps the original client port


<!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_stream_return_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_stream_return_module

Example Configuration
Directives
     return

The ngx_stream_return_module module (1.11.2) allows
sending a specified value to the client and then closing the connection.

Example Configuration

server {
    listen 12345;
    return $time_iso8601;
}

Directives

            Syntax:

            return value;

            Default:

            —

            Context:

            server

Specifies a value to send to the client.
The value can contain text, variables, and their combination.