<!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>What does the following error mean in the log file:                “accept() failed (53: Software caused connection abort)                while accepting new connection on 0.0.0.0:80”?</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

What does the following error mean in the log file:                “accept() failed (53: Software caused connection abort)                while accepting new connection on 0.0.0.0:80”?

Q:
What does the following error mean in the log file: "accept() failed (53:
Software caused connection abort) while accepting new
connection on 0.0.0.0:80"?

A:
Such errors stem from the connections that the clients managed
to close before nginx was able to process them. For instance, this can
happen in a situation when the user didn’t wait for a page
heavily populated with images to load fully, and clicked on a
different link. In this case user’s browser would close all of
the prior connections which aren’t longer necessary.
It is a non-critical error.


<!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>Why nginx doesn’t handle chunked encoding                responses from my backend properly?</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

Why nginx doesn’t handle chunked encoding                responses from my backend properly?

Q:
My backend server appears to send HTTP/1.0 responses using
chunked encoding but nginx doesn’t handle it correctly.
For instance, I’m using nginx as a frontend to my node.js
application and instead of pure JSON from backend, nginx
returns something framed in decimal numbers like

47
{"error":"query error","message":"Parameter(s) missing: user,password"}
0

A:
Your backend violates HTTP specification (see
RFC 2616,
"3.6 Transfer Codings").
The "chunked" transfer-codings must not be used with HTTP/1.0.
You’d need to either fix your backend application or upgrade
to nginx version 1.1.4 and newer, where an additional code
was introduced to handle such erratic backend behavior.


<!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>Can I run nginx with “daemon off” or                “master_process off” settings                in a production environment?</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

Can I run nginx with “daemon off” or                “master_process off” settings                in a production environment?

Q:
Can I run nginx with "daemon off" or "master_process off" settings
in a production environment?

A:
First of all, both "daemon on|off" and "master_process on|off" directives were
intended to be used primarily for nginx code development.

While many people use "daemon off" in production it wasn’t really meant for
that. Since version 1.0.9 it is now quite safe to run nginx in production
with "daemon off", though. Bear in mind that non-stop upgrade is not an
option with "daemon off".

In a development environment, using "master_process off", nginx can run in
the foreground without the master process and can be terminated simply
with ^C (SIGINT). This is somewhat similar to running Apache with
an 'X' command-line option. However you should NEVER run nginx in production
with "master_process off".


<!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>How can nginx copyright be acknowledged                when using nginx as part of a proprietary                software distribution?</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

How can nginx copyright be acknowledged                when using nginx as part of a proprietary                software distribution?

Q:
I’d like to use nginx distribution as part of my proprietary
software package. How can nginx copyright be acknowledged
when using nginx as part of a proprietary software distribution?

A:
The text below should be added to your license conditions,
followed by the text of the applicable 2-clause BSD license described
here.

This product contains software provided by Nginx, Inc. and its contributors.

Also, if your build of nginx includes any of the following 3rd party
products: zlib, PCRE, OpenSSL — it’s worth including their
copyright acknowledgements and disclaimers as well.


<!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>Is there a proper way to use nginx variables to                make sections of the configuration shorter,                using them as macros for making                parts of configuration work as templates?</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

Is there a proper way to use nginx variables to                make sections of the configuration shorter,                using them as macros for making                parts of configuration work as templates?

Q:
Is there a proper way to use nginx variables to make sections of
the configuration shorter, using them as macros for making
parts of configuration work as templates?

A:
Variables should not be used as template macros. Variables are
evaluated in the run-time during the processing of each
request, so they are rather costly compared to plain static
configuration. Using variables to store static strings is also
a bad idea. Instead, a macro expansion and "include" directives
should be used to generate configs more easily and it can be
done with the external tools, e.g. sed + make or any other
common template mechanism.


<!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>Configuring HTTPS servers</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

Configuring HTTPS servers

HTTPS server optimization
SSL certificate chains
A single HTTP/HTTPS server
Name-based HTTPS servers
     An SSL certificate with several names
     Server Name Indication
Compatibility

To configure an HTTPS server, the ssl parameter
must be enabled on
listening sockets
in the server block,
and the locations of the
server certificate
and
private key
files should be specified:

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ...
}

The server certificate is a public entity.
It is sent to every client that connects to the server.
The private key is a secure entity and should be stored in a file with
restricted access, however, it must be readable by nginx’s master process.
The private key may alternately be stored in the same file as the certificate:

    ssl_certificate     www.example.com.cert;
    ssl_certificate_key www.example.com.cert;

in which case the file access rights should also be restricted.
Although the certificate and the key are stored in one file,
only the certificate is sent to a client.

The directives ssl_protocols and
ssl_ciphers
can be used to limit connections
to include only the strong versions and ciphers of SSL/TLS.
By default nginx uses
“ssl_protocols TLSv1.2 TLSv1.3”
and “ssl_ciphers HIGH:!aNULL:!MD5”,
so configuring them explicitly is generally not needed.
Note that default values of these directives were
changed several times.

HTTPS server optimization

SSL operations consume extra CPU resources.
On multi-processor systems several
worker processes
should be run,
no less than the number of available CPU cores.
The most CPU-intensive operation is the SSL handshake.
There are two ways to minimize the number of these operations per client:
the first is by enabling
keepalive
connections to send several
requests via one connection and the second is to reuse SSL session
parameters to avoid SSL handshakes for parallel and subsequent connections.
The sessions are stored in an SSL session cache shared between workers
and configured by the
ssl_session_cache
directive.
One megabyte of the cache contains about 4000 sessions.
The default cache timeout is 5 minutes.
It can be increased by using the
ssl_session_timeout
directive.
Here is a sample configuration optimized for a multi-core system
with 10 megabyte shared session cache:

worker_processes auto;

http {
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;

    server {
        listen              443 ssl;
        server_name         www.example.com;
        keepalive_timeout   70;

        ssl_certificate     www.example.com.crt;
        ssl_certificate_key www.example.com.key;
        ssl_protocols       TLSv1.2 TLSv1.3;
        ssl_ciphers         HIGH:!aNULL:!MD5;
        ...

SSL certificate chains

Some browsers may complain about a certificate signed by a well-known
certificate authority, while other browsers may accept the certificate
without issues.
This occurs because the issuing authority has signed the server certificate
using an intermediate certificate that is not present in the certificate
base of well-known trusted certificate authorities which is distributed
with a particular browser.
In this case the authority provides a bundle of chained certificates
which should be concatenated to the signed server certificate.
The server certificate must appear before the chained certificates
in the combined file:

$ cat www.example.com.crt bundle.crt > www.example.com.chained.crt

The resulting file should be used in the
ssl_certificate directive:

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.chained.crt;
    ssl_certificate_key www.example.com.key;
    ...
}

If the server certificate and the bundle have been concatenated in the wrong
order, nginx will fail to start and will display the error message:

SSL_CTX_use_PrivateKey_file(" ... /www.example.com.key") failed
   (SSL: error:05800074:x509 certificate routines::key values mismatch)

because nginx has tried to use the private key with the bundle’s
first certificate instead of the server certificate.

Browsers usually store intermediate certificates which they receive
and which are signed by trusted authorities, so actively used browsers
may already have the required intermediate certificates and
may not complain about a certificate sent without a chained bundle.
To ensure the server sends the complete certificate chain,
the openssl command-line utility may be used, for example:

$ openssl s_client -connect www.godaddy.com:443
...
Certificate chain
 0 s:/C=US/ST=Arizona/L=Scottsdale/1.3.6.1.4.1.311.60.2.1.3=US
     /1.3.6.1.4.1.311.60.2.1.2=AZ/O=GoDaddy.com, Inc
     /OU=MIS Department/CN=www.GoDaddy.com
     /serialNumber=0796928-7/2.5.4.15=V1.0, Clause 5.(b)
   i:/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc.
     /OU=http://certificates.godaddy.com/repository
     /CN=Go Daddy Secure Certification Authority
     /serialNumber=07969287
 1 s:/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc.
     /OU=http://certificates.godaddy.com/repository
     /CN=Go Daddy Secure Certification Authority
     /serialNumber=07969287
   i:/C=US/O=The Go Daddy Group, Inc.
     /OU=Go Daddy Class 2 Certification Authority
 2 s:/C=US/O=The Go Daddy Group, Inc.
     /OU=Go Daddy Class 2 Certification Authority
   i:/L=ValiCert Validation Network/O=ValiCert, Inc.
     /OU=ValiCert Class 2 Policy Validation Authority
     /CN=http://www.valicert.com//emailAddress=info@valicert.com
...

In this example the subject (“s”) of the
www.GoDaddy.com server certificate #0 is signed by an issuer
(“i”) which itself is the subject of the certificate #1,
which is signed by an issuer which itself is the subject of the certificate #2,
which signed by the well-known issuer ValiCert, Inc.
whose certificate is stored in the browsers’ built-in
certificate base (that lay in the house that Jack built).

If a certificate bundle has not been added, only the server certificate #0
will be shown.

A single HTTP/HTTPS server

It is possible to configure a single server that handles both HTTP
and HTTPS requests:

server {
    listen              80;
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ...
}

Prior to 0.7.14 SSL could not be enabled selectively for
individual listening sockets, as shown above.
SSL could only be enabled for the entire server using the
ssl directive,
making it impossible to set up a single HTTP/HTTPS server.
The ssl parameter of the
listen directive
was added to solve this issue.
The use of the
ssl directive
in modern versions is thus discouraged;
it was removed in 1.25.1.

Name-based HTTPS servers

A common issue arises when configuring two or more HTTPS servers
listening on a single IP address:

server {
    listen          443 ssl;
    server_name     www.example.com;
    ssl_certificate www.example.com.crt;
    ...
}

server {
    listen          443 ssl;
    server_name     www.example.org;
    ssl_certificate www.example.org.crt;
    ...
}

With this configuration a browser receives the default server’s certificate,
i.e. www.example.com regardless of the requested server name.
This is caused by SSL protocol behaviour.
The SSL connection is established before the browser sends an HTTP request
and nginx does not know the name of the requested server.
Therefore, it may only offer the default server’s certificate.

The oldest and most robust method to resolve the issue
is to assign a separate IP address for every HTTPS server:

server {
    listen          192.168.1.1:443 ssl;
    server_name     www.example.com;
    ssl_certificate www.example.com.crt;
    ...
}

server {
    listen          192.168.1.2:443 ssl;
    server_name     www.example.org;
    ssl_certificate www.example.org.crt;
    ...
}

An SSL certificate with several names

There are other ways that allow sharing a single IP address
between several HTTPS servers.
However, all of them have their drawbacks.
One way is to use a certificate with several names in
the SubjectAltName certificate field, for example,
www.example.com and www.example.org.
However, the SubjectAltName field length is limited.

Another way is to use a certificate with a wildcard name, for example,
*.example.org.
A wildcard certificate secures all subdomains of the specified domain,
but only on one level.
This certificate matches www.example.org, but does not match
example.org and www.sub.example.org.
These two methods can also be combined.
A certificate may contain exact and wildcard names in the
SubjectAltName field, for example,
example.org and *.example.org.

It is better to place a certificate file with several names and
its private key file at the http level of configuration
to inherit their single memory copy in all servers:

ssl_certificate     common.crt;
ssl_certificate_key common.key;

server {
    listen          443 ssl;
    server_name     www.example.com;
    ...
}

server {
    listen          443 ssl;
    server_name     www.example.org;
    ...
}

Server Name Indication

A more generic solution for running several HTTPS servers on a single
IP address is
TLS
Server Name Indication extension (SNI, RFC 6066),
which allows a browser to pass a requested server name during the SSL handshake
and, therefore, the server will know which certificate it should use
for the connection.
SNI is currently
supported
by most modern browsers
and is a mandatory-to-implement extension in TLSv1.3,
though may not be used by some old or special clients.

Only domain names can be passed in SNI,
however some browsers may erroneously pass an IP address of the server
as its name if a request includes literal IP address.
One should not rely on this.

In order to use SNI in nginx, it must be supported in both the
OpenSSL library with which the nginx binary has been built as well as
the library to which it is being dynamically linked at run time.
OpenSSL supports SNI since 0.9.8f version if it was built with config option
<nobr>“--enable-tlsext”.</nobr>
Since OpenSSL 0.9.8j this option is enabled by default.
If nginx was built with SNI support, then nginx will show this
when run with the “-V” switch:

$ nginx -V
...
TLS SNI support enabled
...

However, if the SNI-enabled nginx is linked dynamically to
an OpenSSL library without SNI support, nginx displays the warning:

nginx was built with SNI support, however, now it is linked
dynamically to an OpenSSL library which has no tlsext support,
therefore SNI is not available

Compatibility

The SNI support status has been shown by the “-V” switch
since 0.8.21 and 0.7.62.

The ssl parameter of the
listen
directive has been supported since 0.7.14.
Prior to 0.8.21 it could only be specified along with the
default parameter.

SNI has been supported since 0.5.23.

The shared SSL session cache has been supported since 0.5.6.

Version 1.27.3 and later: the default SSL protocols are
TLSv1.2 and TLSv1.3 (if supported by the OpenSSL library).
Otherwise, when OpenSSL 1.0.0 or older is used,
the default SSL protocols are TLSv1 and TLSv1.1.

Version 1.23.4 and later: the default SSL protocols are TLSv1,
TLSv1.1, TLSv1.2, and TLSv1.3 (if supported by the OpenSSL library).

Version 1.9.1 and later: the default SSL protocols are TLSv1,
TLSv1.1, and TLSv1.2 (if supported by the OpenSSL library).

Version 0.7.65, 0.8.19 and later: the default SSL protocols are SSLv3, TLSv1,
TLSv1.1, and TLSv1.2 (if supported by the OpenSSL library).

Version 0.7.64, 0.8.18 and earlier: the default SSL protocols are SSLv2,
SSLv3, and TLSv1.

Version 1.0.5 and later: the default SSL ciphers are
“HIGH:!aNULL:!MD5”.

Version 0.7.65, 0.8.20 and later: the default SSL ciphers are
“HIGH:!ADH:!MD5”.

Version 0.8.19: the default SSL ciphers are
“ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM”.

Version 0.7.64, 0.8.18 and earlier: the default SSL ciphers are

“ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP”.

written by Igor Sysoev
edited by Brian Mercer


<!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>Converting rewrite rules</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

Converting rewrite rules

Converting Mongrel rules

A redirect to a main site

People who during their shared hosting life used to configure
everything using only Apache’s .htaccess files,
usually translate the following rules:

RewriteCond  %{HTTP_HOST}  example.org
RewriteRule  (.*)          http://www.example.org$1

to something like this:

server {
    listen       80;
    server_name  www.example.org  example.org;
    if ($http_host = example.org) {
        rewrite  (.*)  http://www.example.org$1;
    }
    ...
}

This is a wrong, cumbersome, and ineffective way.
The right way is to define a separate server for example.org:

server {
    listen       80;
    server_name  example.org;
    return       301 http://www.example.org$request_uri;
}

server {
    listen       80;
    server_name  www.example.org;
    ...
}

On versions prior to 0.9.1, redirects can be made with:

    rewrite      ^ http://www.example.org$request_uri?;

Another example.
Instead of the “upside-down” logic “all that is not
example.com and is not www.example.com”:

RewriteCond  %{HTTP_HOST}  !example.com
RewriteCond  %{HTTP_HOST}  !www.example.com
RewriteRule  (.*)          http://www.example.com$1

one should simply define example.com, www.example.com,
and “everything else”:

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

server {
    listen       80 default_server;
    server_name  _;
    return       301 http://example.com$request_uri;
}

On versions prior to 0.9.1, redirects can be made with:

    rewrite      ^ http://example.com$request_uri?;

Converting Mongrel rules

Typical Mongrel rules:

DocumentRoot /var/www/myapp.com/current/public

RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ %{DOCUMENT_ROOT}/system/maintenance.html [L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ $1 [QSA,L]

RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*)$ $1/index.html [QSA,L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [QSA,L]

RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]

should be converted to

location / {
    root       /var/www/myapp.com/current/public;

    try_files  /system/maintenance.html
               $uri  $uri/index.html $uri.html
               @mongrel;
}

location @mongrel {
    proxy_pass  http://mongrel;
}


<!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>Using nginx as HTTP load balancer</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

Using nginx as HTTP load balancer

Load balancing methods
Default load balancing configuration
Least connected load balancing
Least time load balancing
Session persistence
Weighted load balancing
Health checks
Further reading

Introduction

Load balancing across multiple application instances is a commonly used
technique for optimizing resource utilization, maximizing throughput,
reducing latency, and ensuring fault-tolerant configurations.

It is possible to use nginx as a very efficient HTTP load balancer to
distribute traffic to several application servers and to improve
performance, scalability and reliability of web applications with nginx.

Load balancing methods

The following load balancing mechanisms (or methods) are supported in
nginx:

round-robin — requests to the application servers are distributed
in a round-robin fashion,

least-connected — next request is assigned to the server with the
least number of active connections,

ip-hash — a hash-function is used to determine what server should
be selected for the next request (based on the client’s IP address).

Default load balancing configuration

The simplest configuration for load balancing with nginx may look
like the following:

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

In the example above, there are 3 instances of the same application
running on srv1-srv3.
When the load balancing method is not specifically configured,
it defaults to round-robin.
All requests are

proxied to the server group myapp1, and nginx applies HTTP load
balancing to distribute the requests.

Reverse proxy implementation in nginx includes load balancing for HTTP,
HTTPS, FastCGI, uwsgi, SCGI, memcached, and gRPC.

To configure load balancing for HTTPS instead of HTTP, just use “https”
as the protocol.

When setting up load balancing for FastCGI, uwsgi, SCGI, memcached, or gRPC, use
fastcgi_pass,
uwsgi_pass,
scgi_pass,
memcached_pass, and
grpc_pass
directives respectively.

Least connected load balancing

Another load balancing discipline is least-connected.
Least-connected allows controlling the load on application
instances more fairly in a situation when some of the requests
take longer to complete.

With the least-connected load balancing, nginx will try not to overload a
busy application server with excessive requests, distributing the new
requests to a less busy server instead.

Least-connected load balancing in nginx is activated when the

least_conn directive is used as part of the server group configuration:

    upstream myapp1 {
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

Least time load balancing

Another load balancing discipline is least-time.
Least-time selects the server with the lowest average response time
and the lowest number of active connections, taking into account
inflight requests.

With the least-time load balancing, nginx selects the server based on
which of the following parameters is specified in the

least_time directive:

header — time to receive the first byte from the server,

last_byte — time to receive the full response from the server,

last_byte inflight — time to receive the full response from
the server, taking into account incomplete requests.

Least-time load balancing in nginx is activated when the

least_time directive is used as part of the server group configuration:

    upstream myapp1 {
        least_time header;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

Session persistence

Please note that with round-robin or least-connected load
balancing, each subsequent client’s request can be potentially
distributed to a different server.
There is no guarantee that the same client will be always
directed to the same server.

If there is the need to tie a client to a particular application server —
in other words, make the client’s session “sticky” or “persistent” in
terms of always trying to select a particular server — the ip-hash load
balancing mechanism can be used.

With ip-hash, the client’s IP address is used as a hashing key to
determine what server in a server group should be selected for the
client’s requests.
This method ensures that the requests from the same client
will always be directed to the same server
except when this server is unavailable.

To configure ip-hash load balancing, just add the
ip_hash
directive to the server (upstream) group configuration:

upstream myapp1 {
    ip_hash;
    server srv1.example.com;
    server srv2.example.com;
    server srv3.example.com;
}

Weighted load balancing

It is also possible to influence nginx load balancing algorithms even
further by using server weights.

In the examples above, the server weights are not configured which means
that all specified servers are treated as equally qualified for a
particular load balancing method.

With the round-robin in particular it also means a more or less equal
distribution of requests across the servers — provided there are enough
requests, and when the requests are processed in a uniform manner and
completed fast enough.

When the
weight
parameter is specified for a server, the weight is accounted as part
of the load balancing decision.

    upstream myapp1 {
        server srv1.example.com weight=3;
        server srv2.example.com;
        server srv3.example.com;
    }

With this configuration, every 5 new requests will be distributed across
the application instances as the following: 3 requests will be directed
to srv1, one request will go to srv2, and another one — to srv3.

It is similarly possible to use weights with the least-connected and
ip-hash load balancing in the recent versions of nginx.

Health checks

Reverse proxy implementation in nginx includes in-band (or passive)
server health checks.
If the response from a particular server fails with an error,
nginx will mark this server as failed, and will try to
avoid selecting this server for subsequent inbound requests for a while.

The
max_fails
directive sets the number of consecutive unsuccessful attempts to
communicate with the server that should happen during
fail_timeout.
By default,
max_fails
is set to 1.
When it is set to 0, health checks are disabled for this server.
The
fail_timeout
parameter also defines how long the server will be marked as failed.
After
fail_timeout
interval following the server failure, nginx will start to gracefully
probe the server with the live client’s requests.
If the probes have been successful, the server is marked as a live one.

Further reading

In addition, there are more directives and parameters that control server
load balancing in nginx, e.g.
proxy_next_upstream,
backup,
down, and
keepalive.
For more information please check our
reference documentation.

Last but not least,
application load balancing,
application health checks,
activity monitoring and
on-the-fly reconfiguration of server groups are available
as part of our paid NGINX Plus subscriptions.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Module ngx_http_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_http_access_module

Example Configuration
Directives
     allow
     deny

The ngx_http_access_module module allows
limiting access to certain client addresses.

Access can also be limited by
password, by the
result of subrequest,
or by JWT.
Simultaneous limitation of access by address and by password is controlled
by the satisfy directive.

Example Configuration

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

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

Directives

            Syntax:

            allow
    address |
    CIDR |
    unix: |
    all;

            Default:

            —

            Context:

            http, server, location, limit_except

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

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

            Syntax:

            deny
    address |
    CIDR |
    unix: |
    all;

            Default:

            —

            Context:

            http, server, location, limit_except

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

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


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

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

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

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_acme_module

Example Configuration
Directives
     acme_issuer
     uri
     account_key
     challenge
     common_name_in_csr
     contact
     external_account_key
     preferred_chain
     profile
     ssl_trusted_certificate
     ssl_verify
     state_path
     accept_terms_of_service
     acme_shared_zone
     acme_certificate
Embedded Variables

The ngx_http_acme_module module implements
the automatic certificate management
(ACMEv2)
protocol.

The source code of the module is available
here.
Download and install instructions are available
here.

The module is also available in a prebuilt
nginx-module-acme
package
and in nginx-plus-module-acme package
as part of our
commercial subscription since 1.29.0.

Example Configuration

resolver 127.0.0.1:53;

acme_issuer example {
    uri         https://acme.example.com/directory;
    contact     admin@example.test;
    state_path  /var/cache/nginx/acme-example;
    accept_terms_of_service;
}

acme_shared_zone zone=ngx_acme_shared:1M;

server {
    listen 443 ssl;
    server_name  .example.test;

    acme_certificate example;

    ssl_certificate       $acme_certificate;
    ssl_certificate_key   $acme_certificate_key;

    # do not parse the certificate on each request
    ssl_certificate_cache max=2;
}

server {
    # listener on port 80 is required to process ACME HTTP-01 challenges
    listen 80;

    location / {
        return 404;
    }
}

Directives

            Syntax:

            acme_issuer name { ... }

            Default:

            —

            Context:

            http

Defines an ACME certificate issuer object.

            Syntax:

            uri uri;

            Default:

            —

            Context:

            acme_issuer

The
directory URL
of the ACME server.
This directive is mandatory.

            Syntax:

            account_key alg[:size] | file;

            Default:

            —

            Context:

            acme_issuer

The account's private key used for request authentication.

Accepted values:

ecdsa:256/384/521
for ES256, ES384, or ES512 JSON Web Signature algorithms

rsa:2048/3072/4096
for RS256.

File path for an existing key, using one of the algorithms above.

The generated account keys are preserved across reloads,
but will be lost on restart unless state_path is configured.

            Syntax:

            challenge type;

            Default:

challenge http-01;

            Context:

            acme_issuer

This directive appeared in version 0.2.0.

Specifies the ACME challenge type to be used for the issuer.

Accepted values:

http-01 (http)

tls-alpn-01 (tls-alpn)

ACME challenges are versioned.
If an unversioned name is specified,
the module automatically selects the latest implemented version.

            Syntax:

            common_name_in_csr on | off;

            Default:

common_name_in_csr off;

            Context:

            acme_issuer

This directive appeared in version 0.4.0.

If enabled, sets the Subject Common Name in the certificate request
to the first DNS name or the first IP address provided.

Enabling this option may result in rejected certificate requests.

Prior to version 0.4.0, the Subject Common Name was always set.

            Syntax:

            contact URL;

            Default:

            —

            Context:

            acme_issuer

Sets an array of URLs that the ACME server can use
to contact the client regarding account issues.
The mailto: scheme will be used
unless specified explicitly.

            Syntax:

            external_account_key kid file;

            Default:

            —

            Context:

            acme_issuer

This directive appeared in version 0.2.0.

Specifies a key identifier kid and a file
with the MAC key for

external account authorization.

The value data:key can be specified
instead of the file, which loads a key directly from
the configuration without using intermediate files.

In both cases, the key is expected to be encoded in

base64url.

            Syntax:

            preferred_chain name;

            Default:

            —

            Context:

            acme_issuer

This directive appeared in version 0.3.0.

Specifies the preferred certificate chain.

If the ACME server offers multiple certificate chains,
prefer the chain with the topmost certificate issued from the
Subject Common Name name.
If there are no matches, the default chain will be used.

            Syntax:

            profile name [require];

            Default:

            —

            Context:

            acme_issuer

This directive appeared in version 0.3.0.

Requests the

certificate profile name from the ACME server.

The require parameter will cause certificate renewals
to fail if the server does not support the specified profile.

            Syntax:

            ssl_trusted_certificate file;

            Default:

            —

            Context:

            acme_issuer

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

            Syntax:

            ssl_verify
    on | off;

            Default:

ssl_verify on;

            Context:

            acme_issuer

Enables or disables verification of the ACME server certificate.

            Syntax:

            state_path path | off;

            Default:

state_path acme_<issuer>;

            Context:

            acme_issuer

Defines a directory for storing the module data
that can be persisted across restarts.
This can improve the load time by skipping some requests on startup,
and avoid hitting request rate limits on the ACME server.

The directory contains sensitive content, such as
the account key, issued certificates, and private keys.

The off parameter (0.2.0) disables storing the account
information and issued certificates on disk.

Prior to version 0.2.0, the state directory was not created by default.

            Syntax:

            accept_terms_of_service;

            Default:

            —

            Context:

            acme_issuer

Agrees to the terms of service under which the ACME server will be used.
Some servers require accepting the terms of service
before account registration.
The terms are usually available on the ACME server's website,
and the URL will be printed to the error log if necessary.

            Syntax:

            acme_shared_zone
    zone=name:size;

            Default:

acme_shared_zone zone=ngx_acme_shared:256k;

            Context:

            http

Allows increasing the size of in-memory storage of the module.
The shared memory zone will be used to store the issued certificates,
keys and challenge data for all the configured certificate issuers.

The default zone size is sufficient to hold approximately
50 ECDSA prime256v1 keys or 35 RSA 2048 keys.

            Syntax:

            acme_certificate
    issuer
    [identifier ...]
    [key=alg[:size]];

            Default:

            —

            Context:

            server

Defines a certificate with the list of identifiers
requested from issuer issuer.

The explicit list of identifiers can be omitted.
In this case, the identifiers will be taken from the
server_name directive
in the same server block.
Not all values accepted in the server_name
are valid certificate identifiers:
regular expressions and wildcards are not supported.

The key parameter sets the type of a generated private key.
Supported key algorithms and sizes:
ecdsa:256 (default),
ecdsa:384,
ecdsa:521,
rsa:2048,
rsa:3072,
rsa:4096.

Embedded Variables

The ngx_http_acme_module module supports embedded variables,
valid in the
server block with the
acme_certificate directive:

$acme_certificate

SSL certificate that can be passed to the
ssl_certificate

$acme_certificate_key

SSL certificate private key that can be passed to
ssl_certificate_key


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

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

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

english

русский

news

about

download

security

documentation

faq

books

community

enterprise

community forum (new)

x.com

blog

njs

ingress controller

gateway fabric

Module ngx_http_addition_module

Example Configuration
Directives
     add_before_body
     add_after_body
     addition_types

The ngx_http_addition_module module is a filter
that adds text before and after a response.
This module is not built by default, it should be enabled with the
--with-http_addition_module
configuration parameter.

Example Configuration

location / {
    add_before_body /before_action;
    add_after_body  /after_action;
}

Directives

            Syntax:

            add_before_body uri;

            Default:

            —

            Context:

            http, server, location

Adds the text returned as a result of processing a given subrequest
before the response body.
An empty string ("") as a parameter cancels addition
inherited from the previous configuration level.

            Syntax:

            add_after_body uri;

            Default:

            —

            Context:

            http, server, location

Adds the text returned as a result of processing a given subrequest
after the response body.
An empty string ("") as a parameter cancels addition
inherited from the previous configuration level.

            Syntax:

            addition_types mime-type ...;

            Default:

addition_types text/html;

            Context:

            http, server, location

This directive appeared in version 0.7.9.

Allows adding text in responses with the specified MIME types,
in addition to “text/html”.
The special value “*” matches any MIME type (0.8.29).