\input texinfo  @c -*- texinfo -*-
@setfilename pound.info
@c %**start of header
@settitle Pound

@defcodeindex op
@defcodeindex kw

@syncodeindex fn cp
@syncodeindex vr cp
@syncodeindex op cp
@syncodeindex kw cp

@include version.texi

@c Editor macros from the ``imprimatur'' package.
@macro deadlink{}
@ (@strong{Editor's note: dangling link})
@end macro

@macro FIXMEREF{text,string}
\text\ @i{\string\}@deadlink{}
@end macro

@macro FIXME-ref{string}
@FIXMEREF{,@i{\string\}}
@end macro

@macro FIXME-pxref{string}
@FIXMEREF{see,@i{\string\}}
@end macro

@macro FIXME-xref{string}
@FIXMEREF{See,@i{\string\}}
@end macro

@ifinfo
@dircategory Network applications
@direntry
* pound: (pound).        Light-weight proxy server.
* poundctl: (pound).     Pound proxy server runtime control.
@end direntry
@end ifinfo
@c %**end of header

@iftex
@finalout
@end iftex

@copying
Copyright @copyright{} 2024--2025 Sergey Poznyakoff

@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled ``GNU Free
Documentation License.''
@end quotation
@end copying

@titlepage
@title Pound
@subtitle version @value{VERSION}, @value{UPDATED}
@author Sergey Poznyakoff.
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

@ifnottex
@node Top
@top Pound

This edition of the @cite{Pound Manual}, last updated
@value{UPDATED}, documents @command{pound} version @value{VERSION}.

@insertcopying
@end ifnottex
@contents

@menu
* Overview::
* Introduction::
* Usage::
* Simple Proxy::
* HTTPS::
* Balancer::
* Worker model::
* Logging::
* Configuration::
* poundctl::
* Metric Families::
* Time and Date Formats::
* GNU Free Documentation License::
* Index::
@ifset WEBDOC
@ifhtml
* This Manual in Other Formats::
@end ifhtml
@end ifset

@detailmenu
 --- The Detailed Node Listing ---

Simple Proxy

* Service selection::
* Request modifications::
* Conditional branches::
* Modifying responses::
* Authentication::
* Redirects::
* Error responses::

Service Selection

* Regular Expressions::
* ACL::

HTTPS

* ACME::
* Redirect HTTP to HTTPS::
* HTTPS backends::

Request balancing

* Sessions::
* Balancer groups::
* Dynamic backends::

Configuration

* Lexical structure::
* Syntax::
* String Expansions::
* Global directives::
* File inclusion::
* Logging configuration::
* Management interface::
* Timeouts::
* ListenHTTP::
* ListenHTTPS::
* Service::
* resolver::

String Expansions

* Backreference Expansion::
* Request Accessors::

Global directives

* Runtime directives::
* Worker Settings::
* Proxy Tuning::
* SSL Settings::
* Regexp Settings::
* ACL definition::

Management Interface

* Service Control::

ListenHTTP

* Listener address::
* Listener-specific limits::
* Error definitions::
* Listener logging::
* Request Modification::
* Response Modification::
* Service definitions::

Request Modification

* Rewrite::

Response Modification

* rewrite response::

Service

* Service Selection Statements::
* Service Request and Response Modification::
* Service Logging::
* Backends::
* Session::
* Other Statements::

Backends

* Backend::
* UseBackend::
* Special Backends::

poundctl

* poundctl commands::
* poundctl remote::
* poundctl config::
* poundctl options::
* poundctl template::

Configuring @command{poundctl}

* multiple servers::

@command{poundctl} template

* Template syntax::
* Pipelines::
* Variables::
* Input object::

Template syntax

* Actions::
* Arguments::

Input object

* Full listing::
* Listener object::
* Service object::
* Backend object::

@end detailmenu
@end menu

@node Overview
@chapter Overview

 @command{Pound} is a reverse proxy, load balancer and HTTPS front-end
for Web servers.  It was developed to provide for even distribution of
load between backend httpd servers and to allow for a convenient SSL
wrapper for those servers that do not offer it natively.

 The core principles of its design are simplicity and safety.
@command{Pound}  is a very small program, easily audited for security
problems.  Normally it runs as a non-privileged user, and can
optionally be run in a chrooted environment.  With several exceptions,
it does not access the hard disk during its runtime.  In short, it
should pose no security threat to the server it runs at.

@cindex Robert Segall
@cindex Segall, Robert
@cindex Apsis
@cindex Rick O'Sullivan
@cindex O'Sullivan, Rick
@cindex Frank Schmirler
@cindex Schmirler, Frank
 The original version of @command{pound} was written by Robert Segall at
Apsis
GmbH@footnote{@uref{https://web.archive.org/web/20221202094441/https://apsis.ch/}}. In
2018, I added support for newer OpenSSL to the
then current version of the program (2.8).  This version of
@command{pound}, hosted on @command{github} was further modified by
Rick O'Sullivan and Frank Schmirler, who added WebSocket support.

 On April 2020, Apsis started development of @command{pound} 3.0 --
essentially an attempt to rewrite program from scratch, introducing
dependencies on some third-party software.

 On 2022-09-19, the development and maintenance of @command{pound} was
officially discontinued and Apsis GmbH was dissolved.  Following that,
I decided to continue development of the program taking my fork as a
base.  I considered the branch 3.0, which emerged for a short time
before the original project was abandoned, to be a failed experiment.
To ensure consistent versioning and avoid confusion, my versioning of
@command{pound} started at number 4.0.

@node Introduction
@chapter Introduction
 The job of a proxy server is to receive incoming HTTP or HTTPS
requests, route them to the corresponding web server (@dfn{backend}),
wait for it to reply and forward the response back to the querying
party.  If more than one backend is configured to serve requests, the
proxy should distribute requests evenly between them, so that each
backend gets a share of requests proportional to its capacity.

@findex pound.cfg
 @command{Pound} gets information about backends and instructions on
HTTP request routing from its configuration file @file{pound.cfg}.  It
is located in the @dfn{system configuration directory}, which is
normally @file{/etc}@footnote{The exact location depends on
compilation options.  When in doubt, examine the output of
@command{pound -V}.}.  Syntactically, the configuration file is a sequence of
@dfn{statements} and @dfn{sections}, separated by arbitrary amount of
empty lines and comments.  A @dfn{simple statement} occupies a single
line and consists of a keyword (@dfn{directive}) and one or more
values separated by whitespace.  A @dfn{section} is a compound
statement that encloses other statements and sections.  Sections begin
with a keyword, optionally followed by arguments, and end with a word
@code{End} on a line by itself.  All keywords are case-insensitive.

@anchor{objects}
 The configuration file defines three kinds of objects:
@dfn{listeners}, @dfn{services}, and @dfn{backends}.  These are
defined as configuration sections.

@cindex listener
 A @dfn{listener} defines IP address (and optionally port),
@command{pound} will be listening on for incoming requests.  It
can also be regarded as a frontend definition.  Listener
declarations start with @code{ListenHTTP} (for plaintext HTTP
frontends) or @code{ListenHTTPS} (for HTTPS frontends) keywords.

@cindex service
@anchor{service intro}
 @dfn{Service} sections define rules that decide to which backend to
route requests received by the listeners.  These rules normally
involve analysis of the requested URL or HTTP headers.  A service may
also contain statements that modify requests or responses.

 Services are normally declared inside listeners.  Thus, when a
listener receives a request, it iterates over its services (in the
order of their appearance in the configuration file) to find the
one that matches the request.  If such a service is found, it receives
the request and eventually passes it on to a backend.

 Services may also be declared outside any listeners, in the
global scope.  Such services are shared between all listeners.  They
are tried if none of the services declared within a listener match the
incoming request.

 Service declarations start with the @code{Service} keyword.

@cindex backend
@cindex backend, regular
@cindex regular backend
 @dfn{Backends} are objects that actually handle requests and produce
responses.  Most often these are @dfn{regular backends}, which declare
IP addresses and ports of servers that are to handle the requests.
Backends are defined inside of services, so that the service that
matched the request routes it to its backend. If more than one backend
is defined within a service, incoming requests will be distributed so
that each backend gets its share of the load.

 Several special backend types are provided, such as emergency
backends, redirects, etc.  Only one special backend can be declared
for a service, and it cannot be used together with other backend
types.

 Thus, an average request processing looks as follows.  First,
a request is received by one of the listeners.  The listener then
iterates over its services, until it finds one that matches the
request.  If no such service was found, the listener retries the
process with the services defined in the global scope.  If no matching
service is found, a 503 error (@samp{Service Unavailable}) is
returned.  Otherwise, if the matching service was found, that service
passes the request to one of its backends.  It may modify the request
before that, if it is instructed so by the configuration.  Once the backend
responds, the service passes the response back to the listener (again,
optionally modifying it, if needed), which finally passes it back to
the querying party.

@node Usage
@chapter Usage
 When started, @command{pound} first parses its configuration file.
If any errors are detected at this stage, it prints the appropriate
diagnostics on the standard error and exits with code 1.  Otherwise,
if the configuration file is OK, @command{pound} opens sockets declared in the
listener sections, detaches itself from the controlling terminal and
starts serving incoming requests.  From that moment on, all diagnostic
messages are reported via @command{syslog} (@pxref{Logging}).

 To check whether the configuration file is correct, run
@command{pound} with the @option{-c} (for @dfn{check}) configuration
option:

@example
pound -c
@end example

 Started this way, @command{pound} will check the configuration file,
report any errors, if found, and exit with status 0 if there are no
errors or 1 otherwise.  The option @option{-v} can be used to increase
the verbosity level.  In particular, it instructs @command{pound} to
print a confirmation message on standard error, if no errors have been
encountered (by default it would exit silently in this case).

 To use alternative configuration file, supply its full pathname with
the @option{-f} option, e.g.:

@example
pound -f /etc/pound/test.cfg
@end example

 If you are experimenting with new configurations, you might want to
run @command{pound} in foreground mode and have it print its
diagnostics on the standard error.  This is done by the @option{-e}
option.  So, for testing purposes, it is quite common to start it this
way:

@example
pound -e
@end example

 Another option, @option{-F}, has similar effect, except that it
honors logging settings from the configuration file
(@pxref{Logging}), i.e. when used with this option,
@command{pound} will remain in foreground, but will report its
messages in accordance with its configuration file.

 The following table summarizes all command line options:

@table @option
@kwindex -c
@item -c
Check configuration file for syntax error and exit.  Exit code
indicates whether the configuration is OK (0) or not (1).

@kwindex -e
@item -e
Start in foreground mode and log to standard error (or standard
output, for messages with LOG_DEBUG and LOG_INFO severity levels).
This option ignores the @code{LogLevel} configuration setting
(@pxref{Logging}).

@kwindex -F
@item -F
Foreground mode.  Do not detach from the controlling terminal after
startup, but remain in the foreground instead.  This overrides the
@code{Daemon} configuration  setting (@pxref{Daemon}).  The log
stream (syslog facility or stderr) requested in the configuration file
remains in effect.

@kwindex -f
@item -f @var{file}
Read configuration from the supplied @var{file}, instead of from the
default location.

@kwindex -h
@item -h
Print short command line usage summary and exit.

@kwindex -p
@item -p @var{file}
Sets location of the @dfn{PID file}.  This is the file where
@command{pound} will write its PID after startup.  This option
overrides the value set by the @code{PIDFile} configuration setting
(@pxref{PIDFile}).

@kwindex -v
@item -v
Verbose mode.  During startup, error messages will be sent to stderr
(stdout, for @code{LOG_DEBUG} and @code{LOG_INFO} severities).  If
@command{pound} is configured to log to syslog, error diagnostics will be
duplicated there as well.  After startup the configuration settings
take effect.

When used with @option{-c} this option also instructs @command{pound}
to print an extra confirmation message on standard error, if there are
no errors in the configuration file.

@kwindex -V
@item -V
Print program version, licensing terms, and configuration flags and
exit with status 0.  You can use this option, in particular, to get
the default values @command{pound} was built with, such as
e.g. configuration file location.

@kwindex -W
@item -W @var{feature}
@itemx -W no-@var{feature}
Enable or disable (if prefixed with @samp{no-}) additional @command{pound}
features.  As of version @value{VERSION}, the following features are
implemented:

@defvr Feature warn-deprecated
When parsing the configuration file, warn if it uses any deprecated
statements.  This is the default.  To suppress deprecation
messages, use @option{-W no-warn-deprecated}.
@end defvr

@anchor{dns}
@defvr Feature dns
Resolve host names found in configuration file and returned in the
@code{Location:} header.  This is the default.

You can use @option{-W no-dns} to disable it, in order to
suppress potentially lengthy network host address lookups.  Make sure
if your configuration file refers to backends only by their IP
addresses in this case.

This setting affects also redirection location rewriting:
@xref{Response Modification, RewriteLocation}.
@end defvr

@defvr Feature include-dir=@var{dir}
@defvrx Feature no-include-dir
This controls the @dfn{include directory}, i.e. the directory where
@command{pound} looks for relative file names referred to in its
configuration file.  @xref{include directory}, for a detailed
discussion of this feature.

Using @option{-W include-dir=@var{dir}} sets the new value of the
include directory.

By default, the system configuration directory is used as include
directory, so that any relative file names are looked up there.  To
disable this, use the @option{-W no-include-dir} option.  This means
that each relative filename used in arguments to the directives in the
configuration file will be looked up in the current working directory.
This is useful mainly in testsuite.
@end defvr
@end table

@node Simple Proxy
@chapter Simple Proxy
 In this chapter we will deploy several simplest proxying
configurations to illustrate the concepts introduced above.

 Suppose you have an HTTP server running on localhost port 8080, and
want to make it accessible from outside.  This is achieved by the
following configuration file:

@example
ListenHTTP
    Address 0.0.0.0
    Port 80
    Service
        Backend
            Address 127.0.0.1
            Port 8080
        End
    End
End
@end example

This configuration consists of three nested sections:
@code{ListenHTTP}, @code{Service}, and @code{Backend}.  Each section
ends with a keyword @code{End} on a line by itself.

The first thing that draws attention are @code{Address} and
@code{Port} statements appearing in both listener and backend sections.
In @code{ListenHTTP} they specify the IP address and port to listen on
for incoming requests.  Address @samp{0.0.0.0} stands for all
available IP addresses@footnote{Strictly speaking, for all available
@emph{IPv4} addresses.  To bind to all available IPv4 and IPv6
addresses, use @samp{::0}.}.  In @code{Backend} section, these keywords
specify the address and port of the remote server, where incoming
requests are to be forwarded.

The @code{Service} section has no matching conditions, so it will
match all requests.

@menu
* Service selection::
* Request modifications::
* Conditional branches::
* Modifying responses::
* Authentication::
* Redirects::
* Error responses::
@end menu

@node Service selection
@section Service Selection
@cindex matching rules
@cindex request matching rules
 To route requests to different servers, multiple services are used.
In this case, each service has one or more @dfn{matching rules},
i.e. statements that define conditions that a request must match in
order to be routed to that particular service.  Syntactically, such
rules have the form:

@example
@var{kw} [@var{options}] "@var{pattern}"
@end example

@noindent
where @var{kw} is a keyword specifying what part of the request is
used in comparison, @var{pattern} is a textual pattern which that
part is matched against, and @var{options} are zero or more flags starting
with a dash sign, which define matching algorithm.

@kwindex Host
 Perhaps the most often used condition is @code{Host}, which compares
the value of the HTTP @samp{Host} header with the given pattern.  By
default it uses exact case-insensitive match:

@example
Host "example.com"
@end example

To treat the pattern as a regular expression, use the @option{-re}
option, as in:

@example
Host -re ".*\\.example\\.com"
@end example

@cindex regular expressions, POSIX
@cindex POSIX regular expressions
Whenever we speak about regular expression we usually mean POSIX extended
regular expressions (@pxref{Extended
regexps, POSIX extended regular expressions, POSIX extended regular expressions,
sed, GNU sed}).  However, other regex types can also be used.  This is
covered in @ref{Regular Expressions}.

Notice the use of double backslashes in the above example.  The
backslash before each dot is needed to match it literally, while another one
protects the first one from being interpreted as an escape character in string
(@pxref{Strings}).

Other useful options are @option{-beg} and @option{-end}, which
enable exact matching at the beginning and end of the value,
correspondingly.  Thus, the @code{Host} statement above can be rewritten
as:

@example
Host -end ".example.com"
@end example

The set of options available for use in matching statements is uniform.
@xref{conditional-option}, for a detailed discussion of available options.

The following configuration snippet illustrates the use of matching
rules to select appropriate service (and, correspondingly, backend).
It will route all requests for @samp{www.example.com} to backend
@samp{192.0.2.1:8080}, and requests for @samp{admin.example.com} to
@samp{192.0.2.4:8080}:

@example
ListenHTTP
    Address 0.0.0.0
    Port 80

    Service
        Host "www.example.com"
        Backend
            Address 192.0.2.1
            Port 8080
        End
    End

    Service
        Host "admin.example.com"
        Backend
            Address 192.0.2.4
            Port 8080
        End
    End
End
@end example

Other matching statements use POSIX regexp matching by default.  These are:

@table @code
@item Header
Compare HTTP header against a pattern.  E.g.

@example
Header "Content-Type:[[:space:]]*text/.*"
@end example

@item URL
Match URL:

@example
URL "/login/.*&name=.*"
@end example

@item Path
Match the path part of the URL:

@example
Path -beg "/login"
@end example

@item Query
Match the query part of the URL.

@item QueryParam
Match the value of a query parameter.  This statement takes two
arguments: parameter name and pattern, e.g.:

@example
QueryParam "type" "(int)|(bool)"
@end example
@end table

@xref{Service Selection Statements}, for a detailed description of these
and other matching statements.

@cindex multiple matching rules
@cindex matching rules, joining
@cindex conditions, joining
@cindex logical @samp{and}, implicit
@cindex conjunction, implicit
Multiple matching rules can be used.  Unless expressly specified
otherwise, they are joined by logical @samp{and} operation.  For example:

@example
Service
    Host "www.example.com"
    URL "^/admin(/.*)?"
    Backend
        Address 192.0.2.4
        Port 8080
    End
End
@end example

This service will be used for requests directed to host name
@samp{www.example.com} whose URL begins with @samp{/admin}, optionally
followed by more path components (such as, e.g. @samp{http://www.example.com/admin/login}).

@anchor{Match in service statement}
@kwindex Match
@cindex logical @samp{or}
@cindex @samp{or}, logical
@cindex logical disjunction
@cindex disjunction, logical
To select a service that matches one of defined rules (i.e. combine the
rules using logical @samp{or}), enclose them in @code{Match OR} block,
as in:

@example
@group
Match OR
    Host "example.com"
    Host "www.example.com"
End
@end group
@end example

@cindex logical @samp{and}
@cindex @samp{and}, logical
@cindex logical @samp{and}, explicit
@cindex logical conjunction, explicit
@cindex conjunction, logical
The argument to @code{Match} can be @samp{OR} or @samp{AND},
specifying logical operation to be used to join the enclosed
statements.  The argument can be omitted, in which case @samp{AND} is
implied.  @code{Match} statements can be nested to arbitrary depth,
which allows for defining criteria of arbitrary complexity.  For
example:

@example
Service
    Match OR
        Host "admin.example.com"
        Match AND
            Host "www.example.com"
            URL "^/admin(/.*)?"
        End
    End
    Backend
        Address 192.0.2.4
        Port 8080
    End
End
@end example

@menu
* Regular Expressions::
* ACL::
@end menu

@node Regular Expressions
@subsection Regular Expressions

@cindex regular expressions, PCRE
@cindex regular expressions, Perl-compatible
@cindex Perl-compatible regular expressions
Request matching directives use POSIX extended regular expressions by
default.  If @command{pound} was compiled with @code{PCRE} or
@code{PCRE2} library, @dfn{Perl-compatible regular expressions} can be
used instead.  This can be done either globally or individually for a
given directive.

@kwindex RegexType
To change regular expression type globally, use the following
directive:

@example
RegexType pcre
@end example

It affects all request matching directives that appear after it in the
configuration file, until next @code{RegexType} directive or end of
file, whichever occurs first.  To change back to POSIX regular
expressions, use @code{posix} argument:

@example
RegexType posix
@end example

Argument to the @code{RegexType} directive is case-insensitive.

Regular expression type can also be selected individually for a
directive, using @option{-posix} or @option{-pcre} flags.  For
example:

@example
Host -pcre -icase "(?<!www\\.)example.org"
@end example

@node ACL
@subsection ACL
  Access control lists, or @dfn{ACLs}, are special request matching
statements that evaluate to true if the request came from one of the
predefined IP addresses.  Access control lists are defined using the
@code{ACL} section statement.  Each line within it defines a single
@dfn{CIDR} enclosed in double quotes.  A CIDR consists of a @dfn{network
address} (IPv4 or IPv6), optionally followed by slash and @dfn{network
mask length}, a decimal number in the range [0,32] for IPv4 and [0.64]
for IPv6.  For example:

@example
@group
ACL
    "127.0.0.1/8"
    "192.0.2.0/25"
End
@end group
@end example

  Such @dfn{anonymous ACLs} can appear anywhere a matching statement
is allowed.

  If an ACL is intended for use in multiple places of the configuration
file, it can be defined as a @dfn{named ACL}.  In a named ACL
declaration, the @code{ACL} keyword is followed by a symbolic name in
double quotes.  This name must uniquely identify this ACL among other
access control lists.  Named ACLs are allowed only in the global
(top-level) scope of a configuration file:

@example
@group
ACL "secure"
    "127.0.0.1/8"
    "192.0.2.0/25"
End
@end group
@end example

  This ACL can then be used in any @code{Service} appearing after its
definition by using the following construct:

@example
ACL "secure"
@end example

  Consider for example the following service declaration:

@example
@group
Service
    ACL "secure"
    Path -beg "/stat"
    Backend
        ...
    End
End
@end group
@end example

  This service will handle requests whose URL starts with  @samp{/stat}, if
they came from one of the IP addresses mentioned in the access control
list with the name @samp{secure}.  Effectively, this means that the
access to that URL is limited to these IP addresses.

@node Request modifications
@section Request modifications
  A service can modify requests before forwarding them to backends.  Several
statements are provided for that purpose:

@table @asis
@item SetHeader
Set a HTTP header.

@item DeleteHeader
Delete a HTTP header.

@item SetURL
Rewrite the request URL.

@item SetPath
Rewrite the path part of the URL.

@item SetQuery
Rewrite the query part of the URL.

@item SetQueryParam
Set a single query parameter.
@end table

For example, the following service declaration will add the header
@samp{X-Resent-By: pound} to each request:

@example
@group
Service
    SetHeader "X-Resent-By: pound"
    Backend
       ...
    End
End
@end group
@end example

@cindex backreference expansion
@cindex expansion, backreference
@cindex parenthesized subexpression
Arguments to request modification statements are expanded before
actual use.  During expansion, references to @dfn{parenthesized
subexpressions} in matching rules are replaced with their actual
values.  @dfn{Parenthesized subexpression} is a part of a regular
expression enclosed in parentheses.  It can be referred to in
string arguments as @samp{$@var{n}}, where @var{n} is its ordinal
number.  Numbers start at one, @samp{$0} referring to the entire string
that matched.

The process of expanding parenthesized subexpressions is called
@dfn{backreference expansion}.

For example, the following condition:

@example
Header "Content-Type: ([^/]+)/(.+)$"
@end example

@noindent
has two subexpressions: @samp{$1} and @samp{$2}.  The following
fragment uses these values to add two query parameters to the URL:

@example
@group
SetQueryParam "type" "$1"
SetQueryParam "subtype" "$2"
@end group
@end example

As a more practical example, the following service rewrites the path
to JPEG and GIF images:

@example
@group
Service
    Path "/([^/]+\\.(jpg|gif))$"
    SetPath "/images/$1"
    ...
End
@end group
@end example

When several matching statements are used, these forms refer to the
last one that matched.  Subexpressions in prior statements can be referred to
using the @samp{$@var{i}(@var{j})} construct.  Here, @var{j} is the
0-based number of the statement, counted from the last one upwards.
For example, given the following statements:

@example
@group
Host -re "www\.(.+)"
Header -icase "^Content-Type: *(.*)"
Path "^/static(/.*)?"
@end group
@end example

@noindent
@samp{$1} refers to the subexpression of @code{Path}, @samp{$1(1)}
to that of @code{Header}, and @code{$1(2)} to that of @code{Host}.

@cindex request accessor
String arguments to @code{Set} statements can also contain
@dfn{request accessors} -- special constructs that are expanded to
particular values from the request.  Syntactically, a request accessor
is @samp{%[@var{name}]}, where @var{name} denotes the request part
to access.  For example, @code{%[url]} expands to entire URL,
@code{%[path]} to the path part of the URL, etc.

Using request accessors, the above example of path modification can
be rewritten as:

@example
@group
Path "\\.(jpg|gif)$"
SetPath "/images%[path]"
@end group
@end example

@xref{Request Accessors}, for a detailed discussions of
available accessors.

@node Conditional branches
@section Conditional branches
@kwindex rewrite
 Conditional request modifications can be organized in logical
branches, each branch being applied only if the request matches
certain condition.  The @code{Rewrite} section encloses a set of
request matching rules followed by one or more request modification
statements, which will be applied if the former match the request.
Optional @code{Else} sub-section, which in turn contains request matching
rules and modification statements, will be tried if those rules don't
match.  Any number of @code{Else} sub-sections is allowed, each one being
tried if the previous ones don't match.

 The example below illustrates this concept.  This configuration
snippet sets different paths depending on the file type and URL used:

@example
Service
    Rewrite
        Header "Content-Type:[[:space:]]+image/.*"
        SetPath "/images%[path]"
    Else
        Match AND
            Host "example.org"
            Path "\\.[^.]+$"
        End
        SetPath "/static%[path]"
    Else
        Path "\\.[^.]+$"
        SetPath "/assets%[path]"
    End
    ...
End
@end example

@node Modifying responses
@section Modifying responses
 The @code{rewrite} statement can also be used to modify responses
received from backends before passing them back to the querying
party.  To indicate this intent, the @code{Rewrite} statement must be
followed by the @code{response} keyword:

@example
@group
Rewrite response
    SetHeader "X-Been-There: pound"
End
@end group
@end example

When modifying responses, only two request modification statements
are allowed: @code{SetHeader} and @code{DeleteHeader}.  The list of
request matching rules is limited as well: @code{Header} and
@code{StringMatch}, plus @code{Match} and @code{Not} conditionals.
Notice that these conditionals operate on the response, and not on the
request, as in previous chapters.  For example:

@example
@group
Rewrite response
    Header "Content-Type:[[:space:]]+text/(.*)"
    SetHeader "X-Text-Type: $1"
End
@end group
@end example

This will insert an additional @code{X-Text-Type} header into the
response.  It will contain the subtype value from the
@code{Content-Type} header of the original response.

@node Authentication
@section Authentication
@cindex authentication, basic
@cindex basic authentication
@cindex RFC 7617
 Along with access control lists, introduced above (@pxref{ACL}),
authentication provides another way to limit access to certain
services.  @command{Pound} supports @dfn{basic authentication}, as
defined in RFC 7617.

 This authentication method relies on the presence of the
@code{Authorization} header in the HTTP request.  If the header is
present, its value specifies the @samp{Basic} authorization method and
contains credentials (username and password) that match one of the
users from the server user database, the request is accepted.
Otherwise a 401 (@samp{Authentication Required}) or 407 (@samp{Proxy
Authentication Required}) response is returned with the
@code{WWW-Authenticate} header requesting basic authentication.

@kwindex BasicAuth
 The @code{BasicAuth} request matching statement verifies if the
@code{Authorization} header is present and provides correct
credentials.  The statement matches the request if so.

@cindex user database
 The @code{BasicAuth} statement takes a single argument, specifying
the name of a file containing @dfn{user database}.  This is a plain-text
file created with @command{htpasswd} or similar utility, i.e. each
non-empty line of it must contain username and password hash separated
by a colon.  Password hash can be one of:

@itemize @bullet
@item Password in plain text.
@item Hash created by the system @code{crypt}(3) function.
@item Password hashed using SHA1 algorithm and encoded in BASE64.
This hash must be prefixed by @samp{@{SHA@}}.
@item @command{Apache}-style @samp{APR1} hash.
@end itemize

 Password file is read on the first authorization attempt, after which
its contents is stored in memory.  @command{Pound} will re-read it if
it notices that the file's modification file has changed, so you need
not restart the daemon if you do any changes to the file.

 Thus, if you put the @code{BasicAuth} statement in each service that
must be accessible to authorized users only, that would do the first
and principal part of the basic authentication scheme: access control.
There remains second part: returning properly formatted 401 response
if the request did not pass authorization.  That can be done using a
combination of the @code{Error} internal backend (@pxref{Error
responses}) and response modification techniques described in the
previous section.

 However, instead of using @code{BasicAuth} in each service requiring
limited access and placing a service generating the 401 response in
the end, it is simpler and less error-prone to use the following
approach:

 Create a service with the following content:

@example
@group
Service
    Not BasicAuth "pound/htpasswd"
    Rewrite response
        SetHeader "WWW-Authenticate: Basic realm=\"Restricted access\""
    End
    Error 401
End
@end group
@end example

 Replace the file name (@file{pound/htpasswd}) and realm name
(@samp{Restricted access}) with the actual values.

 Make sure that all services that need to be protected by basic
authentication are declared after that service.  This way, any request
that does not convey an @code{Authentication} header with credentials
matching an entry from your password file will match this service, and
will be replied to with a properly formatted 401 response, which will
prompt the remote user to authenticate themselves.  On the other hand,
authorized requests will not match this service and will eventually be
handled by one of the services declared after it.

@node Redirects
@section Redirects
@cindex backend, special
@cindex backend, external
@cindex special backend
@cindex internal backend
 Apart from regular backends introduced in previous sections,
@command{pound} provides also several @dfn{special} or @dfn{internal}
backends.  As their name implies, such backends handle requests
and generate responses internally, without forwarding them to any
external entities.

@kwindex redirect
 One of such internal backends is @code{Redirect}.  It generates
responses redirecting the client to another location.  The
statement takes two arguments: a three-digit HTTP status code to
return, and the URL to redirect to:

@example
@group
Service
    Redirect 301 "https://www.gnu.org"
End
@end group
@end example

 Allowed values for the status code are 301, 302, 303, 307 and 308.
This argument is optional: if omitted, 302 is used.

 If the URL argument has no path component (as in the example above),
then the path (and query, if present) components from the original
request will be appended to it.  For example, if the original URL were
@indicateurl{http://example.com/software}, the service above would
redirect it @indicateurl{https://www.gnu.org/software}.

 Otherwise, if the path component is present in the URL argument
(even if it is a mere @samp{/}), then the URL is used as is.  For
example, the following will drop any path and query components from
the URL when redirecting:

@example
Redirect 301 "https://www.gnu.org/"
@end example

 The URL argument is subject to backreference expansion and
request accessor interpretation (@pxref{Request modifications}).  If
any of these are actually used, the above logic is disabled.

 String expansions make it possible to implement complex redirects.
For example, the following redirect swaps the first two path
components of the original URL:

@example
@group
Service
    URL "^/([^/]+)/([^/]+)(/.*)?"
    Redirect "http://%[host]/$2/$1$3"
End
@end group
@end example

 The following is a standard paradigm for redirecting requests from
HTTP to HTTPS:

@example
@group
Service
    Redirect 301 "https://%[host]%[url]"
End
@end group
@end example

@node Error responses
@section Error responses
 Another type of internal backends is @code{Error}, a backend that
generates error responses.  It is useful, for instance, to provide
a custom error status and/or message when no service matches the
request.  Normally, for such cases @command{pound} generates a
standard 503 response (@samp{Service Unavailable}) with the built-in
error page.  You can customize this behavior by using as the last
service a @code{Service} section with @code{Error} backend.
For example:

@example
@group
Service
    Error 404 "pound/404.html"
End
@end group
@end example

 The first argument specifies the HTTP status code to return.
@xref{Error backend}, for more info.

 The second argument is optional.  It supplies the name of a file with
the error page to return along with the response.  The name may be
absolute or relative.  In the latter case, the file will be looked
up in the @dfn{include directory}, a special directory for storing
pound-specific files.  @xref{include directory}.  The file
will be read only once, at program startup.  If you modify the file
and want @command{pound} to notice changes, you will have to restart
it.

 If the second argument is not supplied, the error text is determined
by the @code{ErrorFile @var{code}} statement in the enclosing listener (where
@var{code} is the HTTP code in question).  If it is not supplied, the
built-in default text is used.  @xref{Error definitions}.

@node HTTPS
@chapter HTTPS
 In the previous chapter we have described basic proxying techniques
using plain HTTP listener as an example.  Now we will discuss how to
use HTTPS both for listeners and backends.

 To accept HTTPS requests you need to declare @code{ListenerHTTPS}
listener.  It is similar to plain @code{ListenerHTTP} described above,
except that it requires a @dfn{certificate} to be declared.  For
example:

@example
@group
ListenHTTPS
    Address 0.0.0.0
    Port 443
    Cert "/etc/ssl/priv/example.pem"
    Disable TLSv1
    Ciphers "HIGH:@@STRENGTH:!RSA"
End
@end group
@end example

 The @code{Cert} statement supplies the name of the certificate file
in PEM format.  The file must contain the certificate, intermediate
certificates (if necessary), and certificate private key, in that
order.

 The @code{Cert} argument can also specify a directory, in which case
@code{pound} will scan that directory, trying to read the certificate
from each regular file encountered.  It will report an error if unable
to load the file, so this directory should contain only certificate
files.  The order in which certificate files are read is not
specified.

 Multiple @code{Cert} statements are allowed.  When trying to find the
matching certificate, @command{pound} will stop at the first one whose
@code{CN} matches the requested host name.  Thus, the ordering of
@code{Cert} statements is important.  Normally they should be placed
in most-specific to least-specific order, with wildcard certificates
appearing after host-specific ones.

 @code{Cert} directives must precede all other SSL-specific directives.

 Another important directive is @code{Disable}.  It disables the use
of the specified TLS protocol as well as all protocols older than it.
Usually it is used to disable obsolete protocols.  For example,
the @code{Disable} statement in the example above disables @samp{TLSv1},
@samp{SSLv3}, and @samp{SSLv2}.

 To further tune the strength of your encryption use the @code{Ciphers}
directive.  Its argument is a colon-delimited list of OpenSSL ciphers,
as described in @xref{ciphers,,,ciphers(1)}.  The cipher selection
shown in the example above provides for excellent encryption strength.

@menu
* ACME::
* Redirect HTTP to HTTPS::
* HTTPS backends::
@end menu

@node ACME
@section ACME
@cindex LetsEncrypt
@cindex challenges, ACME
 Automatic Certificate Management Environment (@dfn{ACME}), is a
protocol for automated deployment of HTTPS certificates.  It is
perhaps the most often used method for obtaining SSL certificates
nowadays.  In order to issue certificate for a domain or domains,
the protocol verifies that the web server that is requesting a
certificate actually owns these domains.  This process is based on
various @dfn{challenge types}.

@cindex challenge directory, ACME
@command{Pound} supports
HTTP-01@footnote{@uref{https://letsencrypt.org/docs/challenge-types/#http-01-challenge}}
challenge type.  When issuing a certificate using this challenge type,
the ACME client (a program responsible for periodic certificate
re-issuing) obtains from the authority a challenge file, and
stores it in a predefined @dfn{challenge directory}.  The authority
will then request this file from the webserver using a predefined
URL.  It is supposed that the server will serve it from the file that
has been just written by the agent.  If the server returns the file,
its claim to own the domain is proved and the certificate is issued.

 Configuring @command{pound} to reply to challenge requests is as
simple as putting an @code{ACME} statement to the @code{ListenHTTP}
section of its configuration file.  The statement takes a single
argument -- name of the challenge directory:

@example
@group
ListenHTTP
    Address 0.0.0.0
    Port 80
    ACME "/var/lib/pound/.well-known/acme-challenge"
End
@end group
@end example

Needless to say, your ACME agent and @command{pound} must agree on
this directory location.  Configuration of various ACME agents is
beyond the scope of this document.  Please refer to the documentation
of your agent for further details.

@node Redirect HTTP to HTTPS
@section Redirect HTTP to HTTPS

 Nowadays it is common to redirect all plain HTTP requests to HTTPS
on the same URL.  The method of doing so was described in
@ref{Redirects, HTTP to HTTPS}.  As an example, this section shows
a working HTTPS configuration with such redirect.

@example
ListenHTTP
    Address 0.0.0.0
    Port 80
    Service
        Redirect 301 "https://%[host]%[url]"
    End
End

ListenHTTPS
    Address 0.0.0.0
    Port 443
    Cert "/etc/ssl/priv/example.pem"
    Disable TLSv1
    Service
        Backend
            Address 127.0.0.1
            Port 8080
        End
    End
End
@end example

@node HTTPS backends
@section HTTPS backends

 Backends can use HTTPS as well.  To inform @command{pound} that
communication with the backend goes over an encrypted channel, use
the @code{HTTPS} keyword.  The typical usage is:

@example
@group
Backend
    Address 192.0.2.1
    Port 443
    HTTPS
End
@end group
@end example

 Notice, that unlike other statements, @code{HTTPS} is used without
arguments.

 Additional directives are available for fine-tuning the connection.
If used, they must appear after the @code{HTTPS} directive,

 The @code{Cert} directive specify the client certificate to use when
connecting.  Use it if the backend requires client authentication.

 The @code{Disable} and @code{Ciphers} directives are similar to those
described when discussing @code{ListenHTTPS}: the former disables the
given TLS protocol and all protocols prior to it, and the latter
configures the list of OpenSSL ciphers which the client wishes to
use.  The actual cipher to use will be selected from this list during
negotiation with the backend.

 The example below illustrates the use of these directives:

@example
@group
Backend
    Address 192.0.2.1
    Port 443
    HTTPS
    Disable TLSv1_1
    Cert "/etc/pound/crt/b1.pem"
    Ciphers "HIGH:!RSA"
End
@end group
@end example

@node Balancer
@chapter Request balancing
@cindex balancing
@cindex load balancing
@cindex request balancing
  When several backends are defined in a service, incoming requests
will be distributed among them.  This process is called @dfn{balancing}.
By default, requests are distributed equally.  This can be changed by
assigning them a @dfn{priority} -- a positive integer which assigns a
relative weight of the given backend in the distribution algorithm.
The greater the priority is, the more requests this backend gets from
the total flow.

@cindex balancing strategy
@cindex strategy, request balancing
  The distribution algorithm is defined by @dfn{balancing strategy}.
As of version @value{VERSION}, @command{pound} supports two
strategies: @dfn{weighted random balancing} and @dfn{interleaved
weighted round robin balancing}.

@table @dfn
@cindex Weighted random balancing
@item Weighted Random Balancing

This is the default strategy.  The backend to use for each
request is determined at random, taking into account backend
priorities, so that backends with numerically greater priorities have
proportionally greater chances of being selected than the ones with
lesser priorities.

@cindex Interleaved weighted round robin balancing
@item Interleaved Weighted Round Robin Balancing

This strategy cycles over all active backends, considering each one in
its turn.  An integer ordinal number is assigned to each round, which
is incremented (modulo number of backends) each time a new round is
started.  A backend is assigned a request only if its priority is
greater than the round number.

This strategy offers several advantages compared with the previous
one.  First, it results in a more even distribution of the
requests.  Secondly, the resulting distribution is predictable.
@end table

  Overall, the share of requests a given backend receives can be
estimated as:

@example
@math{P@sub{i} / S(P)}
@end example

@noindent
where @math{P@sub{i}} is the priority of the backend with index
@math{i}, and @math{S(P)} is the sum of all priorities.

  Weighted random balancing is used by default.  Each backend gets the
default priority 5, unless another value is expressly assigned using
the @code{Priority} statement, e.g.:

@example
Service
    Backend
        Address 192.168.0.1
        Port 80
        Priority 1
    End
    Backend
        Address 192.168.0.2
        Port 80
        Priority 9
    End
End
@end example

In this example, backend @command{192.168.0.2} will receive roughly 9
times more requests than backend @command{192.168.0.1}.

@kwindex Balancer
The balancing strategy to use is defined by the @code{Balancer}
keyword, which can appear either in the global scope or within a
@code{Service} section.  Its argument can be one of:

@table @code
@kwindex random
@item random
Use weighted random balancing (default).

@kwindex iwrr
@item iwrr
Use interleaved weighted round robin balancing.
@end table

The @code{Balancer} statement appearing in the global scope defines
balancing strategy for all services that don't have @code{Balancer}
statement on their own.

@menu
* Sessions::
* Balancer groups::
* Dynamic backends::
@end menu

@node Sessions
@section Sessions
 Some web applications attempt to introduce state persistence into the
stateless HTTP protocol, by defining @dfn{sessions} using various
mechanisms, such as specially defined headers, cookies, etc.  For such
applications it is critical that all requests that belong to a single
@dfn{session} be directed to the same server, i.e. backend.  Clearly,
this disrupts the balancer logic, and requires that the proxy be able
to understand the backend's notion of session.

 @command{Pound} is able to detect and track sessions identified by
client address, Basic authentication (user id/password), URL
parameter, cookie, HTTP parameter, and HTTP header value.

@kwindex session
 Session tracking is enabled on a per-service basis by a
@code{Session} section.  The section must contain at least the
@code{Type} directive, which specifies what type of session tracking
to use, and the @code{TTL} directive, supplying session idle timeout
in seconds.

 Session types are case-insensitive.  They are summarized in the table
below:

@table @code
@item IP
The @code{IP} session tracking type instructs @code{pound} to forward
all requests from the same client IP address to the same backend
server:

@example
@group
Session
    Type IP
    TTL  300
End
@end group
@end example

@item Basic
Using this session tracking type, @command{pound} parses the
@code{Authentication} header of each request.  If the header is
present, and specifies the @samp{Basic} authentication type, user ID
is extracted from it.  Requests with the same user ID are forwarded to
the same backend server.

@example
@group
Session
    Type Basic
    TTL  300
End
@end group
@end example

@item URL
This tracking scheme uses the value of URL query parameter to define
a session.  The parameter name is supplied using the @code{ID} directive:

@example
@group
Session
    Type URL
    TTL  300
    ID   "sess"
End
@end group
@end example

In this example, sessions are identified by the @samp{sess} parameter,
The request URL might look like @indicateurl{http://example.org?sess=123}.

@item Cookie
The @code{Cookie} tracking type use a certain cookie to identify
sessions.  The cookie name is given by the @code{ID} directive:

@example
@group
Session
    Type Cookie
    TTL  300
    ID   "sess"
End
@end group
@end example

@item Header
Sessions are identified by the value of HTTP header whose name is
given by the @code{ID} directive, e.g.:

@example
@group
Session
    Type Header
    ID   "X-Session"
    TTL  300
End
@end group
@end example

@item Parm
This is the least useful scheme.  Sessions are identified by HTTP
parameter - a string that appears after a semicolon in the URL, such
as @samp{bar} in @indicateurl{http://foo.com;bar}

@example
@group
Session
    Type PARM
    TTL  300
End
@end group
@end example
@end table

@node Balancer groups
@section Balancer groups
@cindex balancer group
  Backends within each service are grouped in @dfn{balancer groups}.
Each such group is assigned a unique integer @dfn{priority}, which
defines the order in which the groups are tried.  When selecting a
backend, a group with the numerically lesser priority is selected and
a suitable backend is looked up among backends defined in the group,
using one of the balancing strategies discussed above.  If no backend
can be selected (e.g. all backends are unavailable), next group is
tried.  The process continues until either a backend is chosen or
the list of balancer groups is exhausted.

@cindex high availability
  By default, backends declared using the @code{Backend} keyword are
assigned to the balancer group 0.  These are backends used during
normal operation.  Backends declared using the @code{Emergency} keyword
(@pxref{Emergency}) are assigned to the balancer group 65535.  These
backends form a pull of @dfn{high availability} backends, which will
be used if all of the normal backends fail.

  More backend groups can be added using dynamic backends, discussed
in the next section.

@node Dynamic backends
@section Dynamic backends
@cindex dynamic backends
@cindex backends, dynamic
  Normally, when a backend is declared in configuration file, the
value supplied with its @code{Address} statement is resolved at once
and the resulting IP is associated with the backend.  Such backends
are @dfn{static}.  You can also instruct @command{pound} to resolve
the hostname and create as many backends as are the IP addresses it
resolves to.  Such backends are called @dfn{dynamic}.@footnote{Support for
dynamic backends is enabled at compile time and requires the
@uref{http://www.gnu.org/software/adns, GNU adns library}.  If unsure
whether your @command{pound} binary includes it, inspect the
@command{pound -V} output.}  When a dynamic
backend is requested, the @code{Backend} statement defines a
@dfn{matrix} which will be used as a template to generate actual
backends from the data in DNS.  The TTL value of the DNS record (or
records) defines minimum time to live of the generated backends.  When
it expires, DNS will be queried again and backends recreated
according to the changes in its responses@footnote{If necessary, the TTL
value can be changed using the @code{OverrideTTL} configuration
directive.  @xref{Backend, OverrideTTL}.}.

@cindex @code{A} record, DNS
@cindex @code{AAAA} record, DNS
  In the simplest case, a dynamic backend can be created using
@code{A} or @code{AAAA} DNS records.  If several records correspond to
the hostname defined in the @code{Address} statement, @command{pound}
can either create a single backend for each of them, or select one of
them in round-robin fashion and use it to create a backend.  Rest of
backend parameters (port value, priority, etc.) will be taken from its
matrix declaration.

@cindex @code{SRV} record, DNS
@cindex weight, @code{SRV} record
@cindex priority, @code{SRV} record
  A more advanced way to create dynamic backends is using @code{SRV}
records.  Each @code{SRV} record has four associated parameters: priority,
weight, target and port.  The @dfn{priority} value defines the @command{pound}
balancer group where to put generated backends.  @dfn{Weight} is assigned
as the priority for each generated backend@footnote{Notice, that the
@code{SRV} terminology differs from what @command{pound} uses.  What
is called @i{priority} in @code{SRV} defines the @dfn{weight} of the
backend group for @command{pound}, whereas what is called @i{weight}
in @code{SRV} defines the @dfn{priority} of a backend within a group.
This confusion is due to historical reasons, and it would be hard to
avoid it without breaking backward compatibility.}.
Finally, @dfn{target} is used as hostname to obtain IP addresses for
the backends.  For example, suppose the following DNS records are
defined:

@example
@group
$ORIGIN _tcp.example.org.
; _srv  TTL     SRV     prio    weight  port target.
_proxy  60      SRV     10      40      8081 be0.example.org.
_proxy  60      SRV     10      70      8082 be1.example.org.
_proxy  60      SRV     20      10      8081 ha1.example.org.
_proxy  60      SRV     20      10      8081 ha2.example.org.
@end group
@end example

Assuming each of the target hostnames resolves to one IP address,
these records will produce two balancer groups of two backends each,
and will be roughly equivalent to the following statements:

@example
Backend
        Address "be0.example.org"
        Port 8081
        Priority 40
End
Backend
        Address "be1.example.org"
        Port 8082
        Priority 70
End

Emergency
        Address "ha1.example.org"
        Port 8081
        Priority 10
End
Emergency
        Address "ha2.example.org"
        Port 8081
        Priority 10
End
@end example

@cindex @code{SRV} record, 0 weight
  @emph{Notice}, that an SRV record can have a weight of 0.  This will
translate to @command{pound} backend priority 0, which is normally not
allowed (@pxref{Balancer}).  According to RFC 2782, this is the
preferred way of defining weights where ``there isn't any server
selection to do'', whereas ``[i]n the presence of records containing
weights greater than 0, records with weight 0 should have a very small
chance of being selected''.  @command{Pound} handles this as follows:
if all @code{SRV} records have zero weight, priority of the resulting
backends is set to 1.  This makes sure the backend selection algorithm
works and gives each backend equal chance of being selected. This
translation does not take place, however, if at least one of
@code{SRV} records has a weight greater than 0.  Another way to handle
such records is using the @code{IgnoreSRVWeight} configuration
statement, which is discussed below.

@kwindex Resolve
  To declare backend as dynamic, use a symbolic host name in its
@code{Address} statement and add the @code{Resolve} statement with one
of the following values:

@deffn {Dynamic Resolve} first
Resolve the symbolic host name and use first IP from the DNS response
as the address of the created dynamic backend.  Thus, this type will
produce at most one dynamic backend.
@end deffn

@deffn {Dynamic Resolve} all
Resolve the symbolic host name and create one backend for each address
from the DNS response.  This enables load balancing between created
backends.  Each backend will be assigned the same priority.
@end deffn

@deffn {Dynamic Resolve} srv
Obtain @code{SRV} records for the host name and use them to generate
dynamic backends.  Each record produces new  dynamic backend of
@code{Resolve all} type, which creates regular backends as described
above.  The weight field of the @code{SRV} record is mapped to the priority
field of each generated backend.  The priority field determines the
balancer group where the backend will be hosted.
@end deffn

@kwindex Family
When resolving hostnames, both IPv4 and IPv6 addresses are looked for.
You can select the specific address family using the @code{Family}
statement.  Its allowed values are:

@table @code
@item any
@kwindex any, @code{Family} statement
Use all address families available.  This is the default.

@item inet
@kwindex inet, @code{Family} statement
Use only IPv4 addresses (@code{A} DNS records).

@item inet6
@kwindex inet6, @code{Family} statement
Use only IPv6 addresses (@code{AAAA} DNS records).
@end table

  For example:

@example
@group
Backend
        Address "_proxy._tcp.example.org"
        Resolve srv
        Family any
End
@end group
@end example

@kwindex IgnoreSRVWeight
@cindex @code{SRV} records, overriding weight
@cindex weight override, @code{SRV} records
Notice, that you need not supply @code{Port} statement for dynamic
backends of @code{srv} resolve type.  Normally, you don't need to
supply @code{Priority}, either.  However, you may do so, if you wish
to override the weight settings from @code{SRV} records.  In that
case, inform @code{pound} about your decision using the following
statement in @code{Backend} section:

@example
IgnoreSRVWeight true
@end example

There are several possible scenarios when this may be needed.  One of
them is when all @code{SRV} records have weight of 0 (see above) and your
configuration defines one or more regular backends in the same
balancer group as backends generated by those records.  In that case,
the default priority assigned by @command{pound} to those generated
backends (1) may prove to be too low for adequate balancing.  Using
@code{IgnoreSRVWeight} allows you to fix that.  For example:

@example
Service
        Backend
                Address 192.0.2.15
                Port 80
                Priority 8
        End
        Backend
                Address "_proxy._tcp.example.org"
                Resolve srv
                Family any
                IgnoreSRVWeight true
                Priority 5
        End
End
@end example

In this example, backends generated by @code{SRV} records for
domain @samp{_proxy._tcp.example.org} will be assigned priority 5,
no matter what the actual value of @code{SRV} weight field.

@kwindex RetryInterval
Dynamic backends will be updated periodically, when the TTL of the
corresponding DNS records expires.  If the hostname cannot be resolved
or a DNS failure occurs, next update will be scheduled in 600
seconds after the failure.  This interval can be configured using the
@code{RetryInterval} statement in the @code{Backend} section, or
globally, in the @code{Resolver} section (@pxref{resolver}).

@node Worker model
@chapter Worker model
@kwindex WorkerMinCount
Each incoming request is processed by a specific @dfn{worker}, i.e. a
thread in the running program.  Total number of running workers is
controlled by three configuration parameters.  @code{WorkerMinCount}
defines the minimum number of workers that should always be running
(5, by default).  Another parameter, @code{WorkerMaxCount} sets the
upper limit on the number of running workers (it defaults to 128).

@kwindex WorkerMaxCount
At each given moment, a worker can be in one of two states: @dfn{idle}
or @dfn{active} (processing a request).  If an incoming request
arrives when all running workers are active, and total number of
workers is less than @code{WorkerMaxCount}, a new thread is started and
the new request is handed to it.  If the number of active workers has
already reached maximum, the new request is added to the @dfn{request
queue}, where it will wait for a worker to become available to
process it.

@kwindex WorkerIdleTimeout
The third parameter, @code{WorkerIdleTimeout}, specifies maximum time
a thread is allowed to spend in the idle state.  If a worker
remains idle longer than that and total number of workers is greater
than the allotted minimum (@code{WorkerMinCount}), this idle worker is
terminated.

@node Logging
@chapter Logging
 @command{Pound} can send its diagnostic messages to standard error,
syslog, or to both.

@kwindex LogFacility
 Upon startup, while the configuration file is being parsed, the
diagnostics goes to the standard error.  Once it switches to the
operation mode and starts serving requests, diagnostic output is
switched to syslog.  The syslog facility to use is configured via
the @code{LogFacility} configuration directive.  By default,
@samp{daemon} is used.

 When running in foreground mode, the @option{-e} command line option
instructs @command{pound} to use standard error for logging, thus
overriding the settings from the configuration file.

@kwindex LogLevel
 Normally, @command{pound} is not very loquacious in logging: only
errors are reported.  Logging of each incoming request can be
configured using the @code{LogLevel} directive.  It can be used either
in listener scope, in which case it affects only this particular
listener, or in global scope, where it affects all listeners that
don't configure it on their own.  The value of this directive can be
either an integer number in range 0 through 5 (inclusive), or a quoted
string.  Numeric value requests one of the @dfn{built-in
log formats}.  String value refers either to a built-in format name,
or to a user-defined format name.

The built-in formats are:

@table @asis
@item 0
@itemx null
@kwindex null, request logging
No request logging at all.

@item 1
@itemx regular
@kwindex regular, request logging
For each request, its source address, request line and response status
are logged.

@item 2
@itemx extended
@kwindex extended, request logging
In addition to the above, the selected service and backend are shown.

@item 3
@itemx vhost_combined
@kwindex vhost_combined, request logging
Detailed request logging using Apache-style @dfn{Combined} log format.

@item 4
@itemx combined
@kwindex combined, request logging
Same as above, but without virtual host information.

@item 5
@itemx detailed
@kwindex detailed, request logging
Same as @samp{combined}, with additional information about the
selected service and backend.
@end table

@anchor{log format}
@cindex custom log format
@cindex log format, user-defined
@kwindex LogFormat
 If the string argument to @code{LogLevel} is not one of the above, it
must refer to the name of a @dfn{custom format}, defined earlier using
the @code{LogFormat} statement.  This statement takes two string arguments:
the name to be assigned to the new format, and its definition.

@dfn{Format definition} is a character string composed of ordinary
characters (not @samp{%}), which are copied unchanged to the resulting
log message, and conversion specifications, each of which are replaced
by a corresponding piece of information about the request or reply.

Conversion specifications are single characters prefixed with a
percent sign.  Depending on the specification, an optional
@dfn{conversion argument} in curly brackets may appear between
@samp{%} and conversion character.

The following conversion characters are defined:

@deffn {Format specifier} %%
Replaced with the percent sign.
@end deffn

@deffn {Format specifier} %a
@anchor{%a}
Originator IP address of the request.  If the request contains
@code{X-Forwarded-For} header and @code{TrustedIP} ACL is
defined, the value of the header is consulted to obtain the IP
address.  The value must be a comma-delimited list of intermediate
user-agent IP addresses.  To determine the actual user-agent IP, the
list is traversed from right to left, until an IP is found that is not
listed in @code{TrustedIP} ACL.

If @code{X-Forwarded-For} is not present, or @code{TrustedIP}
is not defined, or the above algorithm does not return an IP address,
@code{%a} expands to the actual remote IP address the request came from
(same as @code{%h}).

The @code{TrustedIP} ACL can be defined in global scope, or in
@code{ListenHTTP} (@code{ListenHTTPS}) section, or in @code{Service}
section.  Most-specific ACL overrides least-specific ones, that is
a @code{TrustedIP} defined in @code{Service} will be used, if it is
defined.  If not, the one defined in listener will be used, etc.
The syntax of the @code{TrustedIP} statement is the same as that of
@code{ACL}, i.e.

@example
TrustedIP "@var{name}"
@end example

@noindent
refers to the named ACL @var{name} (which must be defined earlier,
@pxref{ACL}), and

@example
@group
TrustedIP
  "@var{cidr0}"
  "@var{cidr1}"
  ...
End
@end group
@end example

@noindent
defines the list of trusted IPs in place.

If needed, the @code{ForwardedHeader} statement may be used to declare
the name of the header to use instead of @code{X-Forwarded-For}.  As
@code{TrustedIP}, this statement can appear in global, listener, or in
service scope.
@end deffn

@deffn {Format specifier} %A
Local IP address of the listener.
@end deffn

@deffn {Format specifier} %B
Size of response in bytes, excluding headers.
@end deffn

@deffn {Format specifier} %b
Same as @samp{%B}, but in @dfn{CLF} format, i.e. a dash is used when
response size is zero.
@end deffn

@deffn {Format specifier} %D
The time taken to serve the request, in microseconds.
@end deffn

@deffn {Format specifier} %h
Client IP address of the request.
@end deffn

@deffn {Format specifier} %H
The request protocol.
@end deffn

@deffn {Format specifier} %@{@var{hdr}@}i
The contents of @samp{@var{hdr}:} header line in the request.  Changes
made by header modification directives affect this.
@end deffn

@deffn {Format specifier} %@{@var{hdr}@}I
Same as @samp{%i}, except that if no such header is present in the
request, a dash is substituted.
@end deffn

@deffn {Format specifier} %@{@var{obj}@}L
Location of the @command{pound} object that is involved in handling
the request.  Valid values for @var{obj} are: @samp{listener},
@samp{service}, and @samp{backend}.

The location gives position in the configuration file where the object
was defined, and is formatted as

@example
@var{name}:@var{ln1}.@var{col1}-@var{ln2}.@var{col2}
@end example

@noindent
where @var{name} is the configuration file name, @var{ln1} and @var{col1}
are line and column where the object definition begins, @var{ln2} and
@var{col2} are line and column where it ends.  Line and column numbers
start with 1.
@end deffn

@deffn {Format specifier} %m
The request method.
@end deffn

@deffn {Format specifier} %@{@var{obj}@}N
Name of @command{pound} object that is involved in handling the
request.  Valid values for @var{obj} are: @samp{listener},
@samp{service}, and @samp{backend}.
@end deffn

@deffn {Format specifier} %P
Thread ID of the serving thread.
@end deffn

@deffn {Format specifier} %q
The query string (prepended with a @samp{?}) if it exists, otherwise an
empty string.
@end deffn

@deffn {Format specifier} %r
First line of request.
@end deffn

@deffn {Format specifier} %s
Response status code.
@end deffn

@deffn {Format specifier} %>s
First line of the response.
@end deffn

@deffn {Format specifier} %t
Time the request was received, in the format
@samp{[18/Sep/2011:19:18:28 -0400]}.  The last number indicates the
timezone offset from UTC.
@end deffn

@deffn {Format specifier} %@{@var{format}@}t
Time the request was received, in the format specified by the argument
(@pxref{Time and Date Formats}).  If the format starts with
@samp{begin:} (default) the time is taken at the beginning of the
request processing.  If it starts with @samp{end:}, it is the time
after the response from the backend has been sent back to the
requester.  In addition to @code{strftime} formats, the following
specifications are recognized:

@table @asis
@item sec
Number of seconds since the Epoch.
@item msec
Number of milliseconds since the Epoch.
@item usec
Number of microseconds since the Epoch.
@item msec_frac
Millisecond fraction of the time.
@item usec_frac
Microsecond fraction of the time.
@end table
@end deffn

@deffn {Format specifier} %T
The time taken to process the request, in seconds.
@end deffn

@deffn {Format specifier} %@{@var{unit}@}T
The time taken to process the request, in a time unit given by
@var{unit}.  Valid units are @samp{ms} for milliseconds, @samp{us} for
microseconds, @samp{s} for seconds, and @samp{f} for seconds with
fractional part.  Using @samp{s} gives the same result as @samp{%T}
without any format; using @samp{us} gives the same result as @samp{%D}.
@end deffn

@deffn {Format specifier} %u
Remote user if the request was authenticated.
@end deffn

@deffn {Format specifier} %U
The URL path requested.  This is affected by request modification
directives.
@end deffn

@deffn {Format specifier} %v
The listener name.
@end deffn

 The table below describes the built-in formats in terms of format
definitions:

@table @asis
@item 0
@itemx null
@kwindex null, built-in format
@example
""
@end example

@item 1
@itemx regular
@kwindex regular, built-in format
@example
"%a %r - %>s"
@end example

@item 2
@itemx extended
@kwindex extended, built-in format
@example
"%a %r - %>s (%@{Host@}i/%@{service@}N -> %@{backend@}N) %@{f@}T sec"
@end example

@item 3
@itemx vhost_combined
@kwindex vhost_combined, built-in format
@example
"%@{Host@}I %a - %u %t \"%r\" %s %b \"%@{Referer@}i\" \"%@{User-Agent@}i\""
@end example

@item 4
@itemx combined
@kwindex combined, built-in format
@example
"%a - %u %t \"%r\" %s %b \"%@{Referer@}i\" \"%@{User-Agent@}i\""
@end example

@item 5
@itemx detailed
@kwindex detailed, built-in format
(Split in two lines for readability)
@example
"%@{Host@}I %a - %u %t \"%r\" %s %b \"%@{Referer@}i\" \"%@{User-Agent@}i\"
(%@{service@}N -> %@{backend@}N) %@{f@}T sec"
@end example
@end table

@node Configuration
@chapter Configuration
 A configuration file provides @command{pound} with the information
necessary for performing its tasks.  Some configuration file
statements can be overridden from the command line.

@menu
* Lexical structure::
* Syntax::
* String Expansions::
* Global directives::
* File inclusion::
* Logging configuration::
* Management interface::
* Timeouts::
* ListenHTTP::
* ListenHTTPS::
* Service::
* resolver::
@end menu

@node Lexical structure
@section Lexical structure
@cindex lexical structure of the configuration file
 Lexically, the file contains tokens of three types: keywords, values,
and separators.  Blanks, tabs, newlines and comments, collectively called
@dfn{white space} are ignored except as they serve to separate
tokens.  Some white space is required to separate otherwise adjacent
keywords and values.

@cindex comments, configuration file
 @dfn{Comments} may appear anywhere where white space may appear in the
configuration file.  A comment begins with a hash sign (@samp{#}) and
continues to the end of the line.

@cindex keywords, configuration file
 A @dfn{keyword} is a sequence of ASCII letters, digits and
underscores that begins with an ASCII letter or underscore.  Keywords
are always case-insensitive.

@cindex values, configuration file
 There are three kinds of @dfn{values}: numeric values (or
@dfn{numbers}), boolean values, quoted strings, and IP addresses.

@table @dfn
@cindex numbers, configuration file
@item Numbers
 A @dfn{numeric value} is a sequence of decimal digits.

@cindex boolean value, configuration file
@item Booleans
 A @dfn{boolean} is one of the following: @samp{yes}, @samp{true},
@samp{on} or @samp{1}, meaning @dfn{true}, and @samp{no},
@samp{false}, @samp{off}, @samp{0} meaning @dfn{false}.

@cindex quoted string
@cindex escape character
@item Strings
@anchor{Strings}
 A @dfn{quoted string} or @dfn{string}, for short, is a sequence of
characters enclosed in a pair of double quotes.  A backslash
(@samp{\}) appearing within a string acts as an @dfn{escape
character}: if it is followed by a double-quote or another backslash,
it forces the character that follows it to be treated as an ordinary
one.  For example:

@example
"string with \" character"
@end example

 A backslash followed by any character other than @samp{"} or @samp{\}
is removed and a warning to that effect is output.  For example, the
following statement:

@example
user "r\oot"
@end example

@noindent
appearing at line 1 of file @file{pound.cfg} will result in the
following message:

@example
pound.cfg:1.8: unrecognized escape character
@end example

@noindent
and will be treated as

@example
user "root"
@end example

@cindex IP address
@item IP addresses
 IP addresses are IPv4 or IPv6 addresses in numeric form, or hostnames.
@end table

@node Syntax
@section Syntax
 Syntactically, @command{pound} configuration is a sequence of
statements of two kinds: simple and compound.

@cindex simple statement
@cindex statement, simple
@cindex directive
 A @dfn{simple statement} or @dfn{directive} consists of a keyword
followed by a value, located on a single line.  For example:

@example
user "proxy"
@end example

There are some simple statements that don't take any value and thus
consist only of a keyword, e.g.

@example
HTTPS
@end example

@cindex compound statement
@cindex statement, compound
@cindex section
 A @dfn{compound statement} or @dfn{section} encloses one or more
other statements (both simple or compound).  It begins with a keyword,
optionally followed by a value, both located on a single line (similar
to simple directives), followed by any number of subordinate
statements, and ends with a keyword @code{End} on a line by itself.
For example:

@example
@group
Control
    Socket "/run/pound.sock"
    Mode 660
    ChangeOwner true
End
@end group
@end example

Unless specified otherwise, directives may appear in any order.

@node String Expansions
@section String Expansions
 String arguments to some configuration statements undergo several
@dfn{expansions} before use.  The @dfn{backreference expansion}
replaces special notations in the string called @dfn{backreferences}
with corresponding parts of the request recently matched against a
regular expression.  The @dfn{request accessor interpretation}
inserts some fragments of the request URL into the string.

These expansions are discussed in detail below.

@menu
* Backreference Expansion::
* Request Accessors::
@end menu

@node Backreference Expansion
@subsection Backreference expansion
Backreference is a construct that refers to a @dfn{parenthesized
group} within a regular expression matched by one of service
matching directives (@pxref{Service Selection Statements}).  During
backreference expansion, each occurrence of such construct is replaced
with the actual value of that parenthesized group.

Syntactically, backreferences can take two forms.  The construct
@code{$@var{n}}, where @var{n} is a decimal number, refers to
@var{n}th parenthesized subexpression of the most recently matched
statement, and the construct @code{$@var{n}(@var{m})} refers to
@var{n}th parenthesized subexpression in the @var{m}th recently matched
statement.  Numbering of subexpressions starts at 1 (@code{$0} refers
to entire matching string).  Numbering of matches starts at 0.

For example, given the following statements

@example
@group
Host -re "www\\.(.+)"
Header -re -icase "^Content-Type: *(.*)"
Path "^/static(/.*)?"
@end group
@end example

@code{$1} refers to the subgroup of @code{Path}, @code{$1(1)} refers to that of
@code{Header}, and @code{$1(2)} to that of @code{Host}.

Curly braces may be used to avoid incorrectly parsing text fragment
that follows the reference as being its part.  This is useful if the
reference is immediately followed by a decimal digit or opening
parenthesis, as in: @samp{$@{1@}(text)}.

To insert a literal dollar or percent sign in the string, use
@samp{$$} or @samp{$%}, correspondingly.

@node Request Accessors
@subsection Request Accessor Interpretation

@dfn{Request accessor} is a syntactical construct of the form:

@example
%[@var{name}]
@end example

@noindent
where @var{name} denotes a part of the incoming request to access and
square brackets are part of the construct.  Accessors are interpreted and
replaced with the value of the corresponding part of the request.
Some accessors take an argument, which is specified after accessor
name and is delimited from it by one or more whitespace characters.

The following accessors are defined:

@deffn {Accessor} url
Request URL.
@end deffn

@deffn {Accessor} path
Request path.
@end deffn

@deffn {Accessor} query
Query part.
@end deffn

@deffn {Accessor} param @var{name}
The value of the query parameter @var{name}.
@end deffn

@deffn {Accessor} header @var{name}
The value of HTTP header @var{name}.
@end deffn

@deffn {Accessor} host
Hostname part of the @var{Host} header.  If the latter
does not include port number, it is equivalent to
@code{%[header host]}.
@end deffn

@deffn {Accessor} port
If the value of the @code{Host} header includes port number,
@samp{%[port]} expands to port number with the leading colon
character.  Otherwise, it expands to empty string.
@end deffn

@node Global directives
@section Global directives
 Global directives configure the program operation as a whole.  They
may appear anywhere at the global scope of the configuration file,
although it is customary for them to be at its start.

@menu
* Runtime directives::
* Worker Settings::
* Proxy Tuning::
* SSL Settings::
* Regexp Settings::
* ACL definition::
@end menu

@node Runtime directives
@subsection Runtime directives

@deffn {Global directive} Daemon @var{bool}
@anchor{Daemon}
When set to @samp{true} (the default), @command{pound} will detach
itself from the controlling terminal after successful parsing of the
configuration file and continue operating in the background.

When set to @samp{false}, @command{pound} will continue operating in
the foreground.

This setting can be overridden by the @option{-F} and @option{-e}
command line options.
@end deffn

@deffn {Global directive} Group "@var{group_name}"
Sets the group @command{pound} will run as.  If not set, the primary
group of the user (as set by the @code{User} directive) will be used.
@end deffn

@deffn {Global directive} PIDFile "@var{filename}"
@anchor{PIDFile}
Sets the name of the file where to store program PID.  This can be
also be set from command line, using @option{-p} command line option
(@pxref{Usage}).

Notice the following:

@enumerate 1
@item
When running with a supervisor, this file holds PID of the supervisor
process.  Otherwise, it holds PID of the main @comment{pound} process.
This means it is always suitable for signalling the program using the
traditional @command{kill `cat filename`} technique.

@item
Before shutting down, @command{pound} removes this file.  However,
it may fail to do so if it switches to privileges of another user
after startup (at least one of @code{User} or @code{Group} are set in
the configuration file) and the file is stored in a directory whose
permissions forbid write access for that user.
@end enumerate
@end deffn

@deffn {Global directive} Supervisor @var{bool}
When running in daemon mode, start a @dfn{supervisor} process.  This
process, in turn, will start main @command{pound} process and will
further monitor it, restarting it if it fails.

The default is @code{true}.
@end deffn

@deffn {Global directive} RootJail "@var{directory}"
If this directive is present, @command{pound} will use the system
@code{chroot} call to set the root directory of the process to that
specified by @var{directory}.  After that, the program won't be able
to access any files outside that directory.

Before chrooting, @command{pound} makes the necessary preparations to
be able to access the files it needs during operation, in particular
user databases supplied with the @code{BasicAuth} statements
(@pxref{Authentication}).
@end deffn

@deffn {Global directive} User "@var{user_name}"
Configures the user @command{pound} will run as.
@end deffn

@node Worker Settings
@subsection Worker Settings

@deffn {Global directive} WorkerMinCount @var{n}
Sets minimum number of worker threads that must always be running.
The default is 5.  @xref{Worker model}.
@end deffn

@deffn {Global directive} WorkerMaxCount @var{n}
Sets maximum number of worker threads.  The default is 128.
@xref{Worker model}.
@end deffn

@deffn {Global directive} WorkerIdleTimeout @var{n}
Sets idle timeout for a worker thread, in seconds.  Default is 30 seconds.
@xref{Worker model}.
@end deffn

@deffn {Global directive} Threads @var{n}
This statement, retained for backward compatibility with previous
versions of pound, is equivalent to:

@example
WorkerMinCount @var{n}
WorkerMaxCount @var{n}
@end example
@end deffn

@node Proxy Tuning
@subsection Proxy Tuning Directives

@deffn {Global directive} BackendStats @var{bool}
@anchor{BackendStats}
Whether to enable backend statistics collection.  Backend statistics
consists of the following values:

@enumerate 1
@item Total number of requests processed by this backend.
@item Average time per request.
@item Standard deviation of the average time per request.
@end enumerate

If enabled, these values are made available via @command{poundctl}
(@pxref{poundctl list}) and telemetry output (@pxref{Metrics}).
@end deffn

@deffn {Global directive} Balancer @var{algo}
Sets the request balancing algorithm to use.  Allowed values for
@var{algo} are:

@table @asis
@item random
Use weighted random balancing algorithm.

@item iwrr
Use interleaved weighted round robin balancing.
@end table

@xref{Balancer}, for a detailed discussion of these algorithms.

The @code{Balancer} statement in global scope applies to all @code{Service}
definitions in the file that don't contain @code{Balancer} definitions
of their own.
@end deffn

@deffn {Global directive} HeaderOption @var{opt} ...
Sets default header addition options.  One or more arguments are
allowed, each being one of:

@table @code
@item off
Disable additional headers.

@item forwarded
Add @code{X-For-warded-For}, @code{X-Forwarded-Proto}, and
@code{X-Forwarded-Port} headers.

@item ssl
Pass information about SSL certificates in a set of @code{X-SSL-*}
headers.  This will add the following headers:

@table @asis
@item X-SSL-Cipher
SSL version followed by a slash and active cipher algorithm.

@item X-SSL-Certificate
The full client certificate (multi-line).

@item X-SSL-Issuer
Information about the certificate issuer (CA).

@item X-SSL-Subject
Information about the certificate owner.

@item X-SSL-notAfter
End of validity date for the certificate.

@item X-SSL-notBefore
Start of validity date for the certificate.

@item X-SSL-serial
Certificate serial number (in decimal).
@end table
@end table

The default is:

@example
HeaderOption forwarded ssl
@end example

This setting can be overridden for a particular listener using the
@code{HeadOption} within it.
@end deffn

@node SSL Settings
@subsection SSL Settings

@deffn {Global directive} SSLEngine "@var{name}"
Use an OpenSSL hardware acceleration card called @var{name}.  Available
only if OpenSSL-engine is installed on your system.
@end deffn

@deffn {Global directive} ECDHcurve "@var{name}"
Use the named curve for elliptical curve encryption.
@end deffn

@node Regexp Settings
@subsection Regular Expression Settings

@deffn {Global directive} RegexType @var{type}
Sets the type of regular expressions to use in request matching
statements.  Allowed values for @var{type} are: @code{posix} and
@code{pcre} (or @code{perl}), case-insensitive.  The latter requires
compilation time support.

The selected regular expression type remains in effect for all request
matching directives that follow this statement, until next
@code{RegexType} statement or end of the configuration file, whichever
occurs first.

Regular expression type can be set individually for a directive, using
the @code{-pcre} or @code{-posix} option (@pxref{conditional-option}).

@xref{Regular Expressions}, for a detailed discussion.
@end deffn

@deffn {Global directive} IgnoreCase @var{bool}
Ignore case when doing regex matching (default: @samp{false}). This
directive sets the default for the following service matching
directives: @code{URL}, @code{Path}, @code{QueryParam}, @code{Query},
@code{StringMatch}, as well as for the @code{DeleteHeader}
modification directive.  Its value can be overridden for specific services.

This statement is deprecated and will be removed in future versions.
Please, use the @option{-icase} option to the matching directive
instead (@pxref{conditional-option}).
@end deffn

@node ACL definition
@subsection ACL Definition

@deffn {Global directive} ACL "@var{name}"
Define a @dfn{named access control list}.  An @dfn{ACL} is a
list of network addresses in CIDR notation, one address per line,
terminated with an @code{End} directive on a line by itself.  E.g.:

@example
@group
ACL "secure"
   "192.0.2.0/26"
   "203.0.113.0/24"
End
@end group
@end example

The @code{Include} directive is allowed within the ACL section.
Named ACLs can be used in @code{Service} definitions to limit access
to services from certain IP addresses only.  @xref{ACL}, for a
detailed discussion of this.
@end deffn

@node File inclusion
@section File inclusion

@deffn {Global directive} Include "@var{file}"
Include @var{file} as if it were part of the configuration file.  If
@var{file} is a relative file name, it will be looked in the @dfn{include
directory} (see below).

This directive is allowed both at topmost level and in any subsections
of the configuration file.
@end deffn

@deffn {Global directive} IncludeDir "@var{dir}"
@anchor{include directory}
Set the @dfn{include directory}, i.e. the directory where
@command{pound} looks for relative file names that appear in other
configuration directives: @code{Include}, @code{BasicAuth},
@code{ErrorFile} (or @code{Err400} through @code{Err503}), as well as
in the argument to @option{-file} option in service matching directives
(@pxref{-file}).

The default value is the system configuration directory as set at
compile time (you can check its value in the output of @command{pound
-V}).  This initial value can be changed in the command line using the
@option{-W include-dir=@var{dir}} command line option or reset to the
current working directory using the @option{-W no-include-dir} option
(@pxref{Usage}).
@end deffn

@node Logging configuration
@section Logging configuration
@deffn {Global directive} LogFacility @var{name}
@deffnx {Global directive} LogFacility -
Sets the @command{syslog} facility to use for logging.  Allowed names
are: @samp{auth}, @samp{authpriv}, @samp{cron}, @samp{daemon}, @samp{ftp},
@samp{kern}, @samp{lpr}. @samp{mail}, @samp{news},
@samp{user}. @samp{uucp}, and @samp{local0} through @samp{local7}.

The second form configures @dfn{default log destination}.  If
@command{pound} runs in foreground, log messages with priority
@code{LOG_DEBUG} and @code{LOG_INFO} go to stdout, and messages with
the remaining priorities are printed to stderr.  If @command{pound}
runs as a daemon, log messages go to the syslog facility @samp{daemon}.
@end deffn

@deffn {Global directive} LogFormat "@var{name}" "@var{format_def}"
Define request logging format.  @var{name} is a string uniquely
identifying this format, and @var{format_def} is the format string
definition.  @xref{Logging}, for a detailed description of format
definition syntax.
@end deffn

@deffn {Global directive} LogLevel "@var{name}"
@deffnx {Global directive} LogLevel @var{n}
Specify the format to use to log HTTP requests.  @var{name} is a name
of a custom format, defined earlier using the @code{LogFormat}
directive, or one of six built-in format names.

If numeric argument is used, it refers to a built-in format by its
number (0 through 5).

@xref{Logging}, for a detailed description of HTTP request logging.
@end deffn

@deffn {Global directive} LogTag "@var{string}"
Sets the string to tag syslog messages with.  By default, it is the
name of the program (more precisely, the name which was used to start
it).
@end deffn

@deffn {Global directive} ForwardedHeader "@var{name}"
Defines the name of the HTTP header that carries the list of proxies
the request has passed through.  Default value is
@code{X-Forwarded-For}.  This header is used to determine the originator
IP address for logging.  @xref{%a}, for details.
@end deffn

@deffn {Global directive} TrustedIP
Defines a list of @dfn{trusted proxy}
IP addresses, which is used to determine the originator IP.
@xref{%a}, for details.

This statement is a special form of @code{ACL} statement, described
below.  It can appear in two forms: as a @dfn{section} or as a
@dfn{directive}.  When used as a section, it is followed by a list of
one or more CIDRs each appearing on a separate line.  The @code{End}
keyword terminates the statement, e.g.:

@example
@group
TrustedIP
  "127.0.0.1/8"
  "10.16.0.0/16"
End
@end group
@end example

In directive form, this statement takes a single argument, the name of
an access control list defined earlier using the @code{ACL} statement,
e.g.

@example
TrustedIP "proxy_addresses"
@end example
@end deffn

@deffn {Global directive} Anonymise
@deffnx {Global directive} Anonymize
When logging, replace the last byte of client IP addresses with 0.

Default: log the client address in full.
@end deffn

@node Management interface
@section Management Interface
@command{Pound} provides a management interface, which allows one to
obtain information about the running instance, change state of
configured listeners, services, and backends, etc.  These requests are
normally issued by the poundctl utility (@pxref{poundctl}).

@cindex control socket
The management interface is usually made available via a UNIX socket.
Properties of this @dfn{control socket} are configured via the
@code{Control} statement.  It has two forms: @dfn{directive} and
@dfn{section}.

@deffn {Global directive} Control "@var{filename}"
@anchor{Control statement}
Create a UNIX socket @var{filename} and listen on it for management
requests.  The file will be owned by the user that started
@command{pound} (normally @samp{root}) and have mode 0600.
@end deffn

In section form, the @code{Control} statement allows for specifying
file mode and, to certain extent, socket file ownership.  The section
can contain the following statements:

@deffn {Control statement} Socket "@var{filename}"
Specifies the name of the socket file to use.  This is the only
mandatory statement in the section form.
@end deffn

@deffn {Control statement} Mode @var{octal}
Sets the mode of the socket file.
@end deffn

@deffn {Control statement} ChangeOwner @var{bool}
This statement takes effect if at least one of @code{User} or @code{Group}
global statements is used.  When set to @code{true} it will change the
owner of the socket file to that specified by those two statements.
@end deffn

An example of using the @code{Control} section:

@example
@group
Control
    Socket "/run/pound.sock"
    Mode 660
    ChangeOwner true
End
@end group
@end example

@menu
* Service Control::
@end menu

@node Service Control
@subsection Remote Access to Management Interface
@kwindex Control
  To make the management interface available remotely, use the
@code{Control} statement in a @code{Service} section:

@example
@group
ListenHTTP
    Address 192.0.2.1
    Port 80
    Service
        Control
    End
End
@end group
@end example

  This configuration makes management interface accessible via
@indicateurl{http://192.0.2.1/}.  Due to obvious security
implications, you'd be better off protecting the @code{Control}
endpoint using HTTPS, ACLs and/or basic authorization.  The example
below illustrates all these techniques:

@example
ListenHTTPS
    Address 192.0.2.1
    Port 443
    Cert "/etc/ssl/priv/example.pem"
    Disable TLSv1

    Service
        Not BasicAuth "pound/htpasswd"
        Rewrite response
            SetHeader "WWW-Authenticate: Basic realm=\"Restricted access\""
        End
        Error 401
    End

    Service
        ACL "secure"
        Control
    End
End
@end example

@xref{Authentication}, for a discussion of @code{BasicAuth} statement,
and see @ref{ACL} for a discussion of access control lists (this
example assumes that the ACL @samp{secure} is defined elsewhere in the
configuration file).

If you wish to make management interface available under a special
path, make sure the path prefix is stripped off, e.g.:

@example
@group
Service
    URL -re "^/control(/.+)"
    SetURL "$1"
    Control
End
@end group
@end example

@xref{Service Request and Response Modification}, for details about
@code{SetURL} statement and request modification in general.

@node Timeouts
@section Timeouts

Directives discussed in this section set various timeout values.
Their argument is an integer expressing the value in seconds.

@deffn {Global directive} Alive @var{n}
Specify how often should @command{pound} check for the status of
backend servers marked as @dfn{dead} (i.e. inaccessible).  It is a
good idea to set this as low as possible -- it will find resurrected
hosts faster.  However, if you set it too low it will consume
resources.

Default is 30 seconds.
@end deffn

@deffn {Global directive} Client @var{n}
Specify for how long @command{pound} will wait for a client request
(default: 10 seconds).  It will drop the connection if client doesn't
send any data within this interval.

This value can be overridden for specific listeners.
@end deffn

@deffn {Global directive} TimeOut @var{n}
Specify for how long @command{pound} will wait for the backend to
respond (default: 15 seconds).

This value can be overridden for specific backends.
@end deffn

@deffn {Global directive} ConnTO @var{n}
Specify for how long @command{pound} will wait for a connection to
a backend to be established.  Default is the same as the
@code{TimeOut} value.

This value can be overridden for specific backends.
@end deffn

@deffn {Global directive} WSTimeOut @var{n}
Specify for how long @command{pound} will wait for data from either
backend or client in a connection upgraded to WebSocket protocol.
Default is 600 seconds.

This value can be overridden for specific backends.
@end deffn

@deffn {Global directive} Grace @var{n}
How long should @command{pound} continue to answer existing
connections after a receiving a @samp{INT} or @samp{HUP}
signal (default: 30 seconds).  The configured listeners are closed
immediately. You can bypass this behaviour by stopping @command{pound}
with a @samp{TERM} or @samp{QUIT} signal, in which case the program
exits without any delay.
@end deffn

@node ListenHTTP
@section ListenHTTP
@kwindex ListenHTTP
 The @code{ListenHTTP} section declares a listener operating in
plaintext HTTP mode.  The section declaration begins with the
keyword @code{ListenHTTP} optionally followed by a string supplying
symbolic name for that listener, e.g.:

@example
@group
ListenHTTP "main"
  @dots{}
End
@end group
@end example

The symbolic name can be used in log messages (@pxref{log format,
@samp{%@{@var{obj}@}N}}) and in @command{poundctl}
(@pxref{poundctl}) requests to identify that listener.  If the
name is not supplied, the listener can be identified by its ordinal
number (0-based) in the configuration file.

@menu
* Listener address::
* Listener-specific limits::
* Error definitions::
* Listener logging::
* Request Modification::
* Response Modification::
* Service definitions::
@end menu

@node Listener address
@subsection Listener address

@deffn {ListenHTTP directive} Address @var{address}
The IP address that @command{pound} will listen on.  This can be a
numeric IPv4 or IPv6 address, or a full pathname of a UNIX socket.  To
listen on all available interfaces, use @samp{0.0.0.0} (for IPv4), or
@samp{::0} (for both IPv4 and IPv6).

If neither @code{Address} or @code{SocketFrom} are supplied,
@samp{::0} is assumed.
@end deffn

@deffn {ListenHTTP directive} Port @var{n}
@findex /etc/services
The port number or service name (as per @file{/etc/services} that
this listener will listen on.

If this directive is not given, the default port number is assumed (80
for @code{ListenHTTP} and 443 for @code{ListenHTTPS}).
@end deffn

@deffn {ListenHTTP directive} SocketFrom "@var{pathname}"
Read the socket to listen on from the UNIX socket supplied by
@var{pathname}.  If this parameter is supplied, neither @code{Address}
nor @code{Port} may be used.  This parameter is intended for use
in @command{pound} testsuite.
@end deffn

@node Listener-specific limits
@subsection Listener-specific limits

@deffn {ListenHTTP directive} Client @var{n}
Specify for how long @command{pound} will wait for a client request
(default: 10 seconds).  It will drop the connection if client doesn't
send any data within this interval.

This statement overrides the global timeout value (@pxref{Timeouts})
for this particular listener.
@end deffn

@deffn {ListenHTTP directive} MaxRequest @var{n}
Limits the maximum allowed size of incoming requests.
A request bigger than that will be responded with status
413.

By default, there is no limit on the request size.
@end deffn

@deffn {ListenHTTP directive} MaxURI @var{n}
Limits the maximum allowed length of incoming request URI.
A request with an URI longer than that will be responded with status
414.

By default, there is no limit on the URI length.
@end deffn

@deffn {ListenHTTP directive} CheckURL "@var{pattern}"
Define a pattern that must be matched by each request sent to this
listener.  A request that does not match will be returned a 501
status.
@end deffn

@deffn {ListenHTTP directive} xHTTP @var{n}
Defines which HTTP method are accepted. The possible values are:

@table @asis
@item 0
Accept only standard HTTP methods: @code{GET}, @code{POST}, @code{HEAD}.
This is the default.

@item 1
Allow also extended HTTP methods: @code{PUT}, @code{PATCH}, @code{DELETE}.

@item 2
Additionally allow standard WebDAV methods: @code{LOCK}, @code{UNLOCK},
@code{PROPFIND}, @code{PROPPATCH}, @code{SEARCH}, @code{MKCOL},
@code{MOVE}, @code{COPY}, @code{OPTIONS}, @code{TRACE},
@code{MKACTIVITY}, @code{CHECKOUT}, @code{MERGE}, @code{REPORT}.

@item 3
Additionally allow MS extension WebDAV methods: @code{SUBSCRIBE},
@code{UNSUBSCRIBE}, @code{NOTIFY}, @code{BPROPFIND},
@code{BPROPPATCH}, @code{POLL}, @code{BMOVE}, @code{BCOPY},
@code{BDELETE}, @code{CONNECT}.
@end table
@end deffn

@node Error definitions
@subsection Error definitions

When @command{pound} returns an error status, it uses built-in
error-specific description code and status page template.  These
values can be customized using the @code{ErrorFile} statement.

@deffn {ListenHTTP directive} ErrorFile @var{code} "@var{filename}"
Read HTML page for HTTP status code @var{code} from file
@var{filename}.

The @var{code} argument is a three-digit HTTP response status, and
@var{filename} is the name of a file which supplies text of the error
page to be returned.  The file is read once, at program startup.
@end deffn

@kwindex Err400
@kwindex Err401
@kwindex Err403
@kwindex Err404
@kwindex Err413
@kwindex Err414
@kwindex Err500
@kwindex Err501
@kwindex Err503
For compatibility with @command{pound} versions up to 4.11, the
following statement is also recognized:

@example
Err@var{nnn} "@var{filename}"
@end example

@noindent
where @var{nnn} is a three-digit HTTP status code.  This statement
is entirely equivalent to

@example
ErrorFile @var{nnn} "@var{filename}"
@end example

@command{Pound} produces only a subset of all possible status codes,
so not all @var{nnn} codes are allowed.  The discussion below lists
available HTTP codes, along with the error description and default
error page text.

@defvr {HTTP status} 400
@samp{Bad Request}
@*
@quotation
Your browser (or proxy) sent a request that this server could not
understand.
@end quotation
@end defvr

@defvr {HTTP status} 401
@samp{Unauthorized}
@*
@quotation
This server could not verify that you are authorized to access
the document requested.  Either you supplied the wrong credentials
(e.g., bad password), or your browser doesn't understand how to supply
the credentials required.
@end quotation
@end defvr

@defvr {HTTP status} 403
@samp{Forbidden}
@*
@quotation
You don't have permission to access this resource.
It is either read-protected or not readable by the server.
@end quotation
@end defvr

@defvr {HTTP status} 404
@samp{Not Found}
@*
@quotation
The requested URL was not found on this server.
@end quotation
@end defvr

@defvr {HTTP status} 405
@samp{Method Not Allowed}
@*
@quotation
The request method is not supported for the requested resource.
@end quotation
@end defvr

@defvr {HTTP status} 413
@samp{Payload Too Large}
@*
@quotation
The request content is larger than the proxy server is able to
process.
@end quotation
@end defvr

@defvr {HTTP status} 414
@samp{URI Too Long}
@*
@quotation
The length of the requested URL exceeds the capacity limit for this
server.
@end quotation
@end defvr

@defvr {HTTP status} 500
@samp{Internal Server Error}
@*
@quotation
The server encountered an internal error and was unable to complete
your request.
@end quotation
@end defvr

@defvr {HTTP status} 501
@samp{Not Implemented}
@*
@quotation
The server does not support the action requested.
@end quotation
@end defvr

@defvr {HTTP status} 503
@samp{Service Unavailable}
@*
@quotation
The server is temporarily unable to service your request due to
maintenance downtime or capacity problems. Please try again later.
@end quotation
@end defvr

@node Listener logging
@subsection Listener logging

Following statements are similar to the ones described in @ref{Logging
configuration}, but apply only to the listener they appear in.

@deffn {ListenHTTP directive} LogLevel "@var{name}"
@deffnx {ListenHTTP directive} LogLevel @var{n}
Specify the format to use to log HTTP requests.  @var{name} is a name
of a custom format, defined earlier using the @code{LogFormat}
directive, or one of six built-in format names.

If numeric argument is used, it refers to a built-in format by its
number (0 through 5).

@xref{Logging}, for a detailed description of HTTP request logging.
@end deffn

@deffn {ListenHTTP directive} ForwardedHeader "@var{name}"
Defines the name of the HTTP header that carries the list of proxies
the request has passed through.  Default value is
@code{X-Forwarded-For}.  This header is used to determine the originator
IP address for logging.  @xref{%a}, for details.
@end deffn

@deffn {ListenerHTTP directive} TrustedIP
Defines a list of @dfn{trusted proxy}
IP addresses, which is used to determine the originator IP.
@xref{%a}, for details.
@end deffn

@node Request Modification
@subsection Request Modification
The statements discussed in this subsection modify incoming requests prior
to passing them to the backend.  These same set of statements can also
be used in @code{Service} section (@pxref{Service}).  When
appearing in both sections, the directive from @code{ListenHTTP}
(@code{ListenHTTPS}) section are applied first, followed by
directives from the @code{Service} section.  Directives from the same
section are applied in order of their appearance.

@deffn {ListenerHTTP directive} RewriteDestination @var{bool}
If set to @samp{true}, the @code{Destination:} request header will be
changed to point to the backend with the correct protocol.
@end deffn

@deffn {ListenerHTTP directive} SetURL "@var{url}"
Set the URL of the incoming request to @var{url}.
@end deffn

@deffn {ListenerHTTP directive} SetPath "@var{value}"
Set the path part of the URL to the given string.
@end deffn

@deffn {ListenerHTTP directive} SetQuery "@var{value}"
Set the query part of the URL to the given string.  @var{Value} must be
a valid query with the special characters properly encoded using
percent encoding.
@end deffn

@deffn {ListenerHTTP directive} SetQueryParam "@var{name}" "@var{value}"
Set the query parameter @var{name} to the @var{value}.  Value must be
properly encoded if it contains reserved characters.
@end deffn

@deffn {ListenerHTTP directive} SetHeader "@var{name}: @var{value}"
@deffnx {ListenerHTTP directive} HeaderAdd "@var{name}: @var{value}"
@deffnx {ListenerHTTP directive} AddHeader "@var{name}: @var{value}"
Sets the HTTP header.  If the header @var{name} already exists, it
will be overwritten.  Otherwise, new header will be added to the end
of the header list.

The @code{HeaderAdd} and @code{AddHeader} forms are retained for
backward compatibility with earlier @command{pound} versions.  You are
advised against using them.
@end deffn

@deffn {ListenerHTTP directive} DeleteHeader [@var{options}] "@var{pattern}"
Remove from the request all headers matching @var{pattern}.  The
@code{HeaderRemove} and @code{HeadRemove} forms are retained for
backward compatibility with earlier @command{pound} versions.  You are
advised against using them.

By default, @var{pattern} is treated as extended POSIX regular
expression.  The @var{options} argument can be used to alter this.  It consists
of zero or more option flags from the following list:

@float Table, deleteheader-option
@caption{Header matching flags for @code{DeleteHeader} directive}
@multitable @columnfractions .30 .70
@headitem Flag @tab Meaning

@kwindex -beg, DeleteHeader option
@cindex prefix match, @code{DeleteHeader}
@item @code{-beg} @tab Exact match at the beginning of string (prefix match).

@kwindex -case, DeleteHeader option
@cindex case insensitive match, @code{DeleteHeader}
@item @code{-case} @tab Case-sensitive comparison.

@kwindex -contain, DeleteHeader option
@cindex substring match, @code{DeleteHeader}
@item @code{-contain} @tab Delete each header where "@var{pattern}" is
a substring.

@kwindex -end, DeleteHeader option
@cindex suffix match, @code{DeleteHeader}
@item @code{-end} @tab Exact match at the end of string (suffix match).

@kwindex -exact, DeleteHeader option
@cindex exact match, @code{DeleteHeader}
@item @code{-exact} @tab Use exact string match.

@kwindex -icase, DeleteHeader option
@cindex case sensitive match, @code{DeleteHeader}
@item @code{-icase} @tab Case-insensitive comparison.

@kwindex -pcre, DeleteHeader option
@cindex Perl-compatible regular expression match, @code{DeleteHeader}
@cindex PCRE match, @code{DeleteHeader}
@item @code{-pcre} @tab Use Perl-compatible regular expression.
@pxref{Regular Expressions}.

@kwindex -perl, DeleteHeader option
@cindex Perl-compatible regular expression match, @code{DeleteHeader}
@cindex PCRE match, @code{DeleteHeader}
@item @code{-perl} @tab Same as @code{-pcre}.

@kwindex -posix, DeleteHeader option
@cindex posix regular expression match, @code{DeleteHeader}
@item @code{-posix} @tab Use POSIX extended regular expression.
@pxref{Regular Expressions}.

@kwindex -re, DeleteHeader option
@cindex regular expression match, @code{DeleteHeader}
@item @code{-re} @tab Use regular expression match.  This assumes the
default regular expression type, as set by the @code{RegexType}
directive (@pxref{Regular Expressions}).
@end multitable
@end float

The following options are mutually exclusive: @code{-beg},
@code{-contain}, @code{-end}, @code{-exact}, @code{-pcre} (@code{-perl}),
@code{-posix}, @code{-re}.  If more than one of these are used, the
last one takes effect.
@end deffn

@deffn {ListenerHTTP directive} HeaderRemove "@var{pattern}"
@deffnx {ListenerHTTP directive} HeadRemove "@var{pattern}"
These are obsolete keywords, equivalent to

@example
DeleteHeader -icase "@var{pattern}"
@end example
@end deffn

@menu
* Rewrite::
@end menu

@node Rewrite
@subsubsection The @code{rewrite} statement
@kwindex Rewrite
The @code{Rewrite} block statement associates one or more header
modification directives discussed above with @dfn{request matching
directives}, so that request modification takes place only
when the request matches certain conditions.

Syntactically, a @code{Rewrite} section is:

@example
@group
  Rewrite [ request ]
    @var{conditional_directives}@dots{}
    @var{modification_directives}@dots{}
[ Else
    @var{conditional_directives}@dots{}
    @var{modification_directives}@dots{} ]
  End
@end group
@end example

@noindent
where @var{conditional_directives} represents one or more @dfn{request
conditionals} described below and @var{modification_directives} stands
for one or more header modification directives.  The @code{Else} part
is optional; any number of @code{Else} blocks can be supplied, thus
providing for conditional branching.

 The @code{Rewrite} statement is processed sequentially until a branch
is found whose @var{conditional_directives} yield @samp{true}, or
@code{End} is encountered.  If a matching branch is found, its
@var{modification_directives} are applied to the request.

@anchor{request matching directives}
 @dfn{Request matching directives} or @dfn{request conditionals} are special
statements that, being applied to a HTTP request, yield @samp{true} or
@samp{false} depending on whether the request satisfies the condition
described in the directive.  The following conditionals are available:

@deffn {Request Conditional} ACL "@var{name}"
Returns @samp{true} if the source IP matches one of the CIDRs from the
named access control list @var{name}.  The ACL itself must have been
defined earlier (@pxref{ACL definition}).

@xref{ACL}, for a detailed discussion.
@end deffn

@deffn {Request Conditional} ACL
This statement defines an unnamed ACL to match the source IP against.
This line must be followed by one or more lines defining CIDRs, as
described in @ref{ACL definition}.  The ACL definition is finished with an
@code{End} keyword on a line by itself.

Semantically, this statement is equivalent to the named ACL reference
described above.

@xref{ACL}, for a detailed discussion.
@end deffn

@deffn {Request Conditional} BasicAuth "@var{filename}"
Evaluates to @samp{true}, if the incoming request passes basic authorization
as described in RFC 7617.  @var{Filename} is the name of a plain text
file containing usernames and passwords, created with @command{htpasswd}
or similar utility.  Unless the name starts with a slash, it is taken
relative to the @code{IncludeDir} directory (@pxref{include directory}).
The file is cached in the memory on the first authorization attempt,
so that further authorizations do not result in disk operations.  The
file will be re-scanned if @command{pound} notices that its
modification time has changed.

@xref{Authentication}.
@end deffn

@deffn {Request Conditional} Header [@var{options}] "@var{pattern}"
Yields @samp{true}, if the request contains at least one header
matching the given @var{pattern}.  By default, @var{pattern} is treated as
case-insensitive POSIX extended regular expression.  This can be changed by
@var{options}, described below.
@end deffn

@deffn {Request Conditional} Host [@var{options}] "@var{hostname}"
Evaluates to @samp{true}, if the @code{Host} header matches
@var{hostname}.  In the absence of @var{options}, case-insensitive
exact match is assumed, i.e. this construct is equivalent to

@example
Header "Host:[[:space:]]*@var{qhost}"
@end example

@noindent
where @var{qhost} is the @var{hostname} argument in quoted form, i.e. with
all characters that have special meaning in regular expressions escaped.

@xref{conditional-option}, for a detailed discussion of @var{options} and
their effect on matching.

This statement is provided to facilitate handling of @dfn{virtual
hosts}.  @xref{Service selection}, for details.
@end deffn

@deffn {Request Conditional} Path [@var{options}] "@var{pattern}"
Returns @samp{true}, if the path part of the incoming request matches
@var{pattern}.
@end deffn

@deffn {Request Conditional} Query [@var{options}] "@var{pattern}"
Returns @samp{true}, if the query part of the incoming request matches
@var{pattern}.  The argument must be properly percent-encoded, if it
contains whitespace or other non-printable characters.
@end deffn

@deffn {Request Conditional} QueryParam "@var{name}" [@var{options}] "@var{pattern}"
Returns @samp{true}, if the value of the query parameter @var{name}
matches @var{pattern}.

@xref{conditional-option}, for a detailed discussion of @var{options} and
their effect on matching.
@end deffn

@deffn {Request Conditional} StringMatch "@var{string}" [@var{options}] "@var{pattern}"
Expands @var{string} as described in @ref{String Expansions} and matches the
resulting value against @var{pattern}.
@end deffn

@deffn {Request Conditional} URL [@var{options}] "@var{pattern}"
Matches URL of the request.  @var{Pattern} is
treated as case-sensitive extended regular expression, unless
instructed otherwise by @var{options} (see below).
@end deffn

In these directives, @var{options} is a whitespace-delimited list of
zero or more flags from the following table:

@float Table, conditional-option
@caption{Conditional directive flags}
@multitable @columnfractions .30 .70
@headitem Flag @tab Meaning

@kwindex -beg, header matching flag
@cindex prefix match, headers
@item @code{-beg} @tab Exact match at the beginning of string (prefix match).

@kwindex -case, header matching flag
@cindex case insensitive match, headers
@item @code{-case} @tab Case-sensitive comparison.

@kwindex -contain, header matching flag
@cindex substring match, headers
@item @code{-contain} @tab Match if @var{pattern} is a substring of
the original value.

@kwindex -end, header matching flag
@cindex suffix match, headers
@item @code{-end} @tab Exact match at the end of string (suffix match).

@kwindex -exact, header matching flag
@cindex exact match, headers
@item @code{-exact} @tab Use exact string match.

@kwindex -file, header matching flag
@cindex file lookup, headers
@anchor{-file}
@item @code{-file} @tab Treat @var{pattern} as
the name of a file to read patterns from.  If the name is relative, it
will be looked up in the @ref{include directory}.  Patterns are read
from the file line by line.  Leading and trailing whitespace is
removed.  Empty lines and comments (lines starting with @code{#}) are
ignored.

@kwindex -icase, header matching flag
@cindex case sensitive match, headers
@item @code{-icase} @tab Case-insensitive comparison.

@kwindex -pcre, header matching flag
@cindex Perl-compatible regular expression match, headers
@cindex PCRE match, headers
@item @code{-pcre} @tab Use Perl-compatible regular expression.
@pxref{Regular Expressions}.

@kwindex -perl, header matching flag
@cindex Perl-compatible regular expression match, headers
@cindex PCRE match, headers
@item @code{-perl} @tab Same as @code{-pcre}.

@kwindex -posix, header matching flag
@cindex posix regular expression match, headers
@item @code{-posix} @tab Use POSIX extended regular expression.
@pxref{Regular Expressions}.

@kwindex -re, header matching flag
@cindex regular expression match, headers
@item @code{-re} @tab Use regular expression match.  This assumes the
default regular expression type, as set by the @code{RegexType}
directive (@pxref{Regular Expressions}).
@end multitable
@end float

The following options are mutually exclusive: @code{-beg}, @code{-contain},
@code{-end}, @code{-exact}, @code{-pcre} (@code{-perl}),
@code{-posix}, @code{-re}.  If more than one of these are used, the
last one takes effect.

@kwindex Not
Placing the keyword @code{Not} before a header matching directive reverts its
meaning.  For example, the following will match any request whose URL
does not begin with @code{/static/}:

@example
Not URL -beg "/static/"
@end example

@kwindex Match
The @code{Match} block statement can be used to join multiple header
matching directives.  Its syntax is:

@example
Match @var{op}
  @dots{}
End
@end example

@noindent
where @dots{} stands for any number of matching directives, and
@var{op} is a boolean operation: @code{AND} or @code{OR}
(case-insensitive).  For example, the statement

@example
@group
Match OR
  Host "www.example.net"
  Path -beg "/ssl"
End
@end group
@end example

@noindent
will match if the request @code{Host} header has the value
@samp{www.example.net}, or the path part of its URL starts with
@samp{/ssl}.  In contrast, the statement below:

@example
@group
Match AND
  Host "www.example.net"
  Path -beg "/ssl"
End
@end group
@end example

@noindent
will match only if both these conditions are met.  As a syntactical
short-cut, two or more matching statements appearing outside of
@code{Match} are joined by an implicit logical @code{AND}, so that the
latter example is equivalent to:

@example
@group
Host "www.example.net"
Path -beg "/ssl"
@end group
@end example

The @code{Match} statement, like any other matching directive, can be
prefixed with @code{Not}, which reverts its meaning.

@node Response Modification
@subsection Response Modification

@deffn {ListenerHTTP directive} RewriteLocation @var{n}
This statement controls whether @code{Location:} and
@code{Content-location:} headers in HTTP responses are modified before
sending them back to the client.

If @var{n} is 0, both headers are left intact.

If @var{n} is 1, the headers are changed as follows.  If they point to the
backend itself or to the listener (but with the wrong protocol),
the request host name will be used instead.  This is the default.

If @var{n} is 2, do the same, but compare only the backend address;
this is useful for redirecting a request to an HTTPS listener on
the same server as the HTTP listener.

To check whether the location points to the listener or to the
backend, its hostname part is resolved and the obtained IP address (or
addresses) are compared with that of listener or backend.  This
process is affected by the @option{dns} feature setting
(@pxref{dns}).  If it is disabled (@option{-W no-dns} option is
given), no resolving takes place.  In this case the location is deemed
to point to the listener if its hostname part matches that of the
incoming request.  For backends, the hostname is compared with the
value of the @code{ServerName} setting of that backend
(@pxref{ServerName}), if any.
@end deffn

@menu
* rewrite response::
@end menu

@node rewrite response
@subsubsection The @code{Rewrite response} statement.

 A special form of the @code{Rewrite} statement is provided for
modifying headers in the response obtained from a regular backend or
generated with a @code{Error} backend, before sending them back to
the requesting server:

@example
@group
  Rewrite response
    @var{conditional_directives}@dots{}
    @var{modification_directives}@dots{}
[ Else
    @var{conditional_directives}@dots{}
    @var{modification_directives}@dots{} ]
  End
@end group
@end example

 The conditional directives allowed for use in this statement are:

@deffn {Rewrite response conditional} Header [@var{options}] "@var{pattern}"
Returns @samp{true}, if the response contains at least one header
matching the given @var{pattern}.
@end deffn

@deffn {Rewrite response conditional} StringMatch "@var{string}" [@var{options}] "@var{pattern}"
Expands @var{string} as described in @ref{String Expansions}, and matches the
resulting value against @var{pattern}.
@end deffn

  Both conditionals treat their @var{pattern} argument as
case-insensitive POSIX extended regular expression.
@xref{conditional-option}, for a discussion of available @var{options}.

  The following @dfn{response modification} directives are defined:

@deffn {Response modification} DeleteHeader [@var{options}] "@var{pattern}"
Remove matching headers from the response.  By
default, @var{pattern} is treated as extended POSIX regular
expression.  Use @var{options} to alter this behavior.
@xref{deleteheader-option}, for a list of available options.
@end deffn

@deffn {Response modification} SetHeader "@var{name}: @var{value}"
Sets the HTTP response header.  Argument
undergoes string expansion (@xref{String Expansions}).  If the header
@var{name} already exists, it will be overwritten.  Otherwise, new
header will be added to the end of the header list.
@end deffn

@node Service definitions
@subsection Service definitions
@kwindex Service definitions
The @code{Service} section defines rules that decide to which backend to
route requests received by that listener.  Any number of
@code{Service} section can be present.  When a request is received,
the listener iterates over all services in the order of their
appearance in the configuration and applies the section rules to the
request.  If the rules match the request, the request is forwarded to
the backend defined in that section.

@xref{Service}, for a detailed discussion of the @code{Service}
statement.

@deffn {ListenHTTP statement} ACME @var{dir}
This statement defines a special service with a built-in backend for
handling @samp{ACME} challenge requests.  @xref{ACME}, for a detailed
discussion of its use.

The @var{dir} argument defines the directory where to look for
challenge files.
@end deffn

@node ListenHTTPS
@section ListenHTTPS
@kwindex ListenHTTPS

The @code{ListenHTTPS} section defines a listener that operates in
HTTPS.  The section declaration begins with the keyword @code{ListenHTTPS}
optionally followed by a string supplying symbolic name for that
listener:

@example
@group
ListenHTTPS "main"
  ...
End
@end group
@end example

The purpose of the symbolic name is the same as in @code{ListenHTTP}
statement.  All keywords defined for @code{ListenHTTP} can be used
for @code{ListenHTTPS} as well.  @xref{ListenHTTP}, for a detailed
discussion of these.

Statements specific for this section are:

@deffn {ListenHTTPS} Cert "@var{filename}"
Specifies the server @dfn{certificate}.  @var{Filename} is either a
certificate file name, or the name of a directory containing certificate files.

A @dfn{certificate file} is a file containing the certificate,
possibly a certificate chain and the signature for this server, in
that order.

This directive is mandatory within @code{ListenHTTPS}.

Multiple @code{Cert} directives are allowed.  If multiple directives
are used, the first one is the default certificate, with additional
certificates used if the client requests them.

The ordering of the directives is important: the first certificate
where the CN matches the client request will be used, so put your
directives in the most-specific-to-least specific order (i.e. wildcard
certificates after host-specific certificates).

@code{Cert} directives must precede all other SSL-specific directives.
@end deffn

@anchor{ClientCert}
@deffn {ListenHTTPS} ClientCert @var{mode} @var{depth}
Specifies whether the listener must ask for the client's HTTPS
certificate.  Allowed values for @var{mode} are:

@enumerate 0
@item Never ask for the certificate (the default).
@item Ask for the client certificate.
@item Ask and fail, if no certificate was presented.
@item Ask but do not verify.
@end enumerate

@var{Depth} is the depth of verification for a client certificate (up
to 9). The default depth limit is 9, allowing for the peer certificate
and additional 9 CA certificates that must be verified.
@end deffn

@deffn {ListenHTTPS} Disable @var{proto}
@kwindex SSLv2
@kwindex SSLv3
@kwindex TLSv1
@kwindex TLSv1_1
@kwindex TLSv1_2
Disable the SSL protocol @var{proto} and all lower protocols as well.
Allowed values for @var{proto} are: @code{SSLv2}, @code{SSLv3},
@code{TLSv1}, @code{TLSv1_1}, @code{TLSv1_2}.

For example:

@example
Disable TLSv1
@end example

This disables SSLv2, SSLv3 and TLSv1, thus allowing only TLSv1_1
and TLSv1_2.
@end deffn

@deffn {ListenHTTPS} Ciphers "@var{cipher_list}"
This is the list of ciphers that will be accepted by the SSL
connection; it is a string in the same format as in @command{OpenSSL}
@code{ciphers} and @code{SSL_CTX_set_cipher_list} functions.
@end deffn

@deffn {ListenHTTPS} SSLHonorCipherOrder @var{bool}
If set @code{true}, the server will broadcast a preference to use
ciphers in the order supplied in the @code{Ciphers} directive.  If the
value is @code{false}, the server will accept any cipher from the
@code{Ciphers} list.  Default value is @code{false}.
@end deffn

@deffn {ListenHTTPS} SSLAllowClientRenegotiation @var{mode}
If @var{mode} is 0, client initiated renegotiation will be disabled.
This will mitigate DoS exploits based on client renegotiation,
regardless of the patch status of clients and servers related to
@dfn{Secure renegotiation}.  If @var{mode} is 1, secure renegotiation is
supported.  If @var{mode} value is 2, insecure renegotiation is supported.

The default value is 0.
@end deffn

@deffn {ListenHTTPS} CAlist "@var{filename}"
Set the list of trusted CA's for this server.  The @var{filename} is
the name of a file containing a sequence of CA certificates (in PEM
format).  The names of the defined CA certificates will be sent to the
client on connection.
@end deffn

@deffn {ListenHTTPS} VerifyList "@var{filename}"
Set the certificate authority list. The @var{filename} is the name of
a file with CA root certificates, in PEM format.
@end deffn

@emph{Please note}, that there is an important difference between the
@code{CAlist} and the @code{VerifyList}.  The @code{CAlist} tells the
client (browser) which client certificates it should send.  The
@code{VerifyList} defines which CAs are actually used for the
verification of the returned certificate.

@deffn {ListenHTTPS} CRLlist "@var{filename}"
Set the @dfn{Certificate Revocation List} file.  @var{Filename} is the
name of a file that contains the CRLs (in PEM format).
@end deffn

@deffn {ListenHTTPS} NoHTTPS11 @var{mode}
Behave like an @code{HTTP/1.0} server for HTTPS clients.  If @var{mode} is
0, always conform to HTTPS/1.1.  If it is 1, do not allow multiple
requests on SSL connections.  If the value is 2 (default), disable multiple
requests on SSL connections only for MSIE clients.
@end deffn

@node Service
@section Service
  The @code{Service} statements define backends to use and conditions
a request should satisfy in order to be routed to these backends.
These statements can appear both within @code{ListenHTTP}
(@code{ListenHTTPS}) sections and outside of them.  When processing an
incoming request, the listener will first try to match it against
services defined within it.  If none of these services matches the
request, it will try to match it against services defined in the top
level.  If a matching service is found, it will be used to process the
request.  Otherwise a 503 (@dfn{Service Unavailable}) response will be
returned.

  A service is defined by a section statement that begins with the
@code{Section} keyword, followed by service definition statements and
terminated by @code{End} on a line by itself:

@example
@group
Service "@var{name}"
  @dots{}
End
@end group
@end example

  Optional @var{name} argument assigns a symbolic name to the
service.  That name is used to identify the service in diagnostic
and access log messages (@pxref{log format, @samp{%@{@var{obj}@}N}}),
metric output (@pxref{Metrics}), and in @command{poundctl}
requests (@pxref{poundctl}).  In the absence of an assigned
@var{name}, the ordinal number of the service in the enclosing section
is used as its identifier.  Service numbers start at 0.

  Following subsections discuss statements that can be used in
@code{Service} sections.

@menu
* Service Selection Statements::
* Service Request and Response Modification::
* Service Logging::
* Backends::
* Session::
* Other Statements::
@end menu

@node Service Selection Statements
@subsection Service Selection Statements
  Service selection statements define conditions an incoming request
must satisfy in order to be handled by this service.

@deffn {Service Conditional} ACL "@var{name}"
Returns @samp{true} if the source IP of the request matches one of the
CIDRs from the named access control list @var{name}.  The ACL itself
must have been defined earlier (@pxref{ACL definition}).

@xref{ACL}, for a detailed discussion.
@end deffn

@deffn {Service Conditional} ACL
This statement defines an unnamed ACL to match the source IP against.
This line must be followed by one or more lines defining CIDRs, as
described in @ref{ACL definition}.  The ACL definition is finished with an
@code{End} keyword on a line by itself.

Semantically, this statement is equivalent to the named ACL reference
described above.

@xref{ACL}, for a detailed discussion.
@end deffn

@deffn {Service Conditional} BasicAuth "@var{filename}"
Evaluates to @samp{true}, if the incoming request passes basic authorization
as described in RFC 7617.  @var{Filename} is the name of a plain text
file containing usernames and passwords, created with @command{htpasswd}
or similar utility.  Unless the name starts with a slash, it is taken
relative to the @code{IncludeDir} directory (@pxref{include directory}).
The file is cached in the memory on the first authorization attempt,
so that further authorizations do not result in disk operations.  The
file will be rescanned if @command{pound} notices that its
modification time has changed.

@xref{Authentication}.
@end deffn

@anchor{ClientCert conditional}
@deffn {Service Conditional} ClientCert "@var{filename}"
Evaluates to @samp{true} if the client presents the certificate
matching that from the file @var{filename} (PEM format).

This conditional cannot be used in standalone services (i.e. services
that are defined in global scope).  It also cannot be used if the
@code{ListenHTTPS} section that hosts the service has the
@code{ClientCert} statement on its own.
@end deffn

@deffn {Service Conditional} Header [@var{options}] "@var{pattern}"
Yields @samp{true}, if the request contains at least one header
matching the given @var{pattern}.  By default, @var{pattern} is treated as
case-insensitive POSIX extended regular expression.  This can be changed by
@var{options}, described below.
@end deffn

@deffn {Service Conditional} Host [@var{options}] "@var{hostname}"
Evaluates to @samp{true}, if the @code{Host} header matches
@var{hostname}.  In the absence of @var{options}, case-insensitive
exact match is assumed, i.e. this construct is equivalent to

@example
Header "Host:[[:space:]]*@var{qhost}"
@end example

@noindent
where @var{qhost} is the @var{hostname} argument in quoted form, i.e. with
all characters that have special meaning in regular expressions escaped.

@xref{conditional-option}, for a detailed discussion of @var{options} and
their effect on matching.

This statement is provided to facilitate handling of @dfn{virtual
hosts}.  @xref{Service selection}, for details.
@end deffn

@deffn {Service Conditional} Path [@var{options}] "@var{pattern}"
Returns @samp{true}, if the path part of the incoming request matches
@var{pattern}.
@end deffn

@deffn {Service Conditional} Query [@var{options}] "@var{pattern}"
Returns @samp{true}, if the query part of the incoming request matches
@var{pattern}.  The argument must be properly percent-encoded, if it
contains whitespace or other non-printable characters.
@end deffn

@deffn {Service Conditional} QueryParam "@var{name}" [@var{options}] "@var{pattern}"
Returns @samp{true}, if the value of the query parameter @var{name}
matches @var{pattern}.

@xref{conditional-option}, for a detailed discussion of @var{options} and
their effect on matching.
@end deffn

@deffn {Service Conditional} StringMatch "@var{string}" [@var{options}] "@var{pattern}"
Expands @var{string} as described in @ref{String Expansions}, and matches the
resulting value against @var{pattern}.
@end deffn

@deffn {Service Conditional} URL [@var{options}] "@var{pattern}"
Matches URL of the request.  @var{Pattern} is
treated as case-sensitive extended regular expression, unless
instructed otherwise by @var{options} (see below).
@end deffn

The @var{options} argument in the directives discussed above defines
the comparison algorithm used.  It consists of one or more flags
described in @ref{conditional-option}.

@kwindex Not
Placing the keyword @code{Not} before a header matching directive reverts its
meaning.  For example, the following will match any request whose URL
does not begin with @code{/static/}:

@example
Not URL -beg "/static/"
@end example

@kwindex Match
The @code{Match} block statement can be used to join multiple header
matching directives.  Its syntax is:

@example
Match @var{op}
  @dots{}
End
@end example

@noindent
where @dots{} stands for any number of matching directives, and
@var{op} is a boolean operation: @code{AND} or @code{OR}
(case-insensitive).  @xref{Match in service statement}, for a detailed
discussion with examples.

@node Service Request and Response Modification
@subsection Request and Response Modification
  These statements modify incoming requests prior to passing them to
the backend.  A similar set of statements can be used in listeners
(@pxref{Request Modification}).  In case both the listener and service
contain request modification statements, those from the listener are
applied first, followed by the ones from the service.

@deffn {Service directive} SetURL "@var{url}"
Set the URL of the incoming request to @var{url}.
@end deffn

@deffn {Service directive} SetPath "@var{value}"
Set the path part of the URL to the given string.
@end deffn

@deffn {Service directive} SetQuery "@var{value}"
Set the query part of the URL to the given string.  @var{Value} must be
a valid query with the special characters properly encoded using
percent encoding.
@end deffn

@deffn {Service directive} SetQueryParam "@var{name}" "@var{value}"
Set the query parameter @var{name} to the @var{value}.  The value must be
properly encoded if it contains reserved characters.
@end deffn

@deffn {Service directive} SetHeader "@var{name}: @var{value}"
@deffnx {Service directive} HeaderAdd "@var{name}: @var{value}"
@deffnx {Service directive} AddHeader "@var{name}: @var{value}"
Sets the HTTP header.  If the header @var{name} already exists, it
will be overwritten.  Otherwise, new header will be added to the end
of the header list.

The @code{HeaderAdd} and @code{AddHeader} forms are retained for
backward compatibility with earlier @command{pound} versions.  You are
advised against using them.
@end deffn

@deffn {Service directive} DeleteHeader [@var{options}] "@var{pattern}"
@deffnx {Service directive} HeaderRemove [@var{options}] "@var{pattern}"
@deffnx {Service directive} HeadRemove [@var{options}] "@var{pattern}"
Remove from the request all headers matching @var{pattern}.  The
@code{HeaderRemove} and @code{HeadRemove} forms are retained for
backward compatibility with earlier @command{pound} versions.  You are
advised against using them.

By default, @var{pattern} is treated as extended POSIX regular
expression.  The @var{options} argument can be used to alter this.  It
consists of zero or more option flags, described in
@ref{deleteheader-option}.
@end deffn

@deffn {Service statement} Rewrite [ request | response ] ... End
This block statement associates one or more header modification
directives discussed above with @dfn{request matching directives}, so that
request modification takes place only when the request matches certain
conditions.

By default @code{Rewrite} statements apply to incoming requests.  The
subject of rewriting can also be specified explicitly after the
@code{Rewrite} keyword.

@xref{Rewrite}, for a detailed discussion of this statement.

@xref{Conditional branches}, for an in-depth discussion with examples.

@xref{Modifying responses}, for a discussion of the use of this
statement to modify responses.
@end deffn

@node Service Logging
@subsection Service Logging

@deffn {Service directive} ForwardedHeader "@var{name}"
Defines the name of the HTTP header that carries the list of proxies
the request has passed through.  Default value is
@code{X-Forwarded-For}.  This header is used to determine the originator
IP address for logging.  @xref{%a}, for details.
@end deffn

@deffn {Service directive} TrustedIP
Defines a list of @dfn{trusted proxy} IP addresses, which is used to
determine the originator IP.

@xref{%a}, for a detailed discussion.

This statement is a special form of @code{ACL} statement, described
in @ref{ACL}.  It can appear in two forms: as a @dfn{section} or as a
@dfn{directive}.  When used as a section, it is followed by a list of
one or more CIDRs each appearing on a separate line.  The @code{End}
keyword terminates the statement, e.g.:

@example
@group
TrustedIP
  "127.0.0.1/8"
  "10.16.0.0/16"
End
@end group
@end example

In directive form, this statement takes a single argument, the name of
an access control list defined earlier using the @code{ACL} statement,
e.g.

@example
TrustedIP "proxy_addresses"
@end example
@end deffn

@anchor{LogSuppress}
@deffn {Service directive} LogSuppress @var{class} [@var{class}...]
 Suppresses HTTP logging for requests that resulted in status codes
from the specified classes.  Valid classes are:

@table @asis
@kwindex info, log suppression
@item info
@itemx 1
@samp{1xx} response codes.

@kwindex success, log suppression
@item success
@itemx 2
@samp{2xx} response codes.

@kwindex redirect, log suppression
@item redirect
@itemx 3
@samp{3xx} response codes.

@kwindex clterr, log suppression
@item clterr
@itemx 4
@samp{4xx} response codes.

@kwindex srverr, log suppression
@item srverr
@itemx 5
@samp{5xx} response codes.

@kwindex all, log suppression
@item all
All response codes.
@end table

This statement is designed for services that receive a constant stream
of similar HTTP requests from a controlled set of IP addresses, such
as e.g. Openmetric  services.  @xref{Metrics}, for an example.
@end deffn

@node Backends
@subsection Backends

@menu
* Backend::
* UseBackend::
* Special Backends::
@end menu

@node Backend
@subsubsection Backend
@kwindex Backend
  The @code{Backend} section defines a regular backend.  The overall
syntax, as for any section statement, is:

@example
@group
Backend [ "@var{name}" ]
  @dots{}
End
@end group
@end example

  Optional @var{name} argument assigns a symbolic name to the
service.  That name is used to identify the backend in diagnostic
and access log messages (@pxref{log format, @samp{%@{@var{obj}@}N}}),
metric output (@pxref{Metrics}), and in @command{poundctl}
requests (@pxref{poundctl}).  In the absence of an assigned
@var{name}, the ordinal (0-based) number of the backend in the enclosing
@code{Service} is used as its identifier.

  The following statements can be used in a @code{Backend} section:

@deffn {Backend directive} Address @var{IP}
  IP address or host name of the backend server.  If the name cannot
be resolved to a valid address, @command{pound} will assume that it
represents a path to a Unix-domain socket.

This directive is mandatory.
@end deffn

@deffn {Backend directive} Disabled @var{bool}
Mark this backend as disabled.

Backends can be enabled or disabled at runtime using the
@command{poundctl} utility (@pxref{poundctl commands, enable}).

@emph{Note:} not to be confused with the @code{Disable} statement,
described below.
@end deffn

@deffn {Backend directive} Port @var{n}
Sets the port number to connect to.  This directive must be present if
the @code{Address} statement contains an IP address.
@end deffn

@deffn {Backend directive} Priority @var{n}
Sets numeric priority for this backend.  Priorities are used to
control probability of receiving a request for handling in case of
multiple backends.  @xref{Balancer}, for a detailed discussion.

Allowed values for @var{n} are 1 to 65535.
@end deffn

Following directives configure @dfn{dynamic backends}.  @pxref{Dynamic
backends}, for a detailed discussion:

@deffn {Backend directive} Family @var{name}
Defines the address family to look for when resolving hostnames:

@table @code
@item any
Use all address families available.  This is the default.

@item inet
Use only IPv4 addresses.

@item inet6
Use only IPv6 addresses.
@end table
@end deffn

@deffn {Backend directive} IgnoreSRVWeight @var{bool}
When using @code{SRV} records, ignore their @i{weight} fields.
Instead, copy priority of the producing backend to generated
backends.

This directive is valid when used together with @code{Resolve srv}
(see below).
@end deffn

@deffn {Backend directive} OverrideTTL @var{n}
This directive configures update interval (in seconds) for dynamic
backends (@pxref{Dynamic backends}).  At the end of each update
interval, the DNS be queried and dynamic backends reconfigured (if
needed) according to its responses.  By default, the TTL value
obtained from previous DNS response is used.

To configure the interval to retry failed DNS lookups, see
@code{RetryInterval}, below.
@end deffn

@deffn {Backend directive} Resolve @var{type}
Declares a dynamic backend.  Valid values
for @var{type} are

@table @code
@item first
Resolve the symbolic host name and use first IP from the DNS response
as the address of the created dynamic backend.  Thus, this type will
produce at most one dynamic backend.

@item all
Resolve the symbolic host name and create one backend for each address
from the DNS response.  This enables load balancing between created
backends.  Each backend will be assigned the same priority.

@item srv
Obtain @code{SRV} records for the host name and use them to generate
dynamic backends.  Each record produces new  dynamic backend of
@code{Resolve all} type, which creates regular backends as described
above.  The weight field of the @code{SRV} record is mapped to the priority
field of each generated backend.  The priority field determines the
balancer group where the backend will be hosted.
@end table
@end deffn

@deffn {Backend directive} RetryInterval @var{n}
Retry failed DNS lookups in @var{n} seconds.  Default is 600.

See also the @code{RetryInterval} statement in @code{Resolver} section
(@pxref{resolver}).
@end deffn

The following three directives set various timeout parameters for
backend operations:

@deffn {Backend directive} ConnTO @var{n}
Sets @dfn{connection timeout}, i.e. time to wait for establishing
connection with the backend (in seconds).
@end deffn

@deffn {Backend directive} TimeOut @var{n}
Sets the @dfn{response timeout}, i.e. time to wait for a response from
the backend (in seconds).  Default is 15.
@end deffn

@deffn {Backend directive} WSTimeOut @var{n}
Idle timeout for WebSocket operations, in seconds.  Default value: 600
(10 minutes).
@end deffn

Backend servers can use HTTPS as well as plaintext HTTP.  The
following directives configure HTTPS backends:

@deffn {Backend directive} HTTPS
This directive indicates that the remote server speaks HTTPS.
@end deffn

@deffn {Backend directive} Cert "@var{filename}"
This specifies the certificate that @command{pound} will use as a
client. The @var{filename} is the name of a file containing the
certificate, possibly a certificate chain and the signature.
@end deffn

@deffn {Backend directive} Ciphers "@var{cipherlist}"
This is the list of ciphers that will be accepted by the SSL
connection with the backend (for HTTPS backends); it is a string in the same format as used by the OpenSSL
functions @code{ciphers} and @code{SSL_CTX_set_cipher_list}.
@end deffn

@deffn {Backend directive} Disable @var{proto}
@kwindex SSLv2
@kwindex SSLv3
@kwindex TLSv1
@kwindex TLSv1_1
@kwindex TLSv1_2
Disable the SSL protocol @var{proto} and all earlier protocols.
Allowed values for @var{proto} are: @code{SSLv2}, @code{SSLv3},
@code{TLSv1}, @code{TLSv1_1}, @code{TLSv1_2}.

@emph{Note:} not to be confused with the @code{Disabled} statement,
described above.
@end deffn

@anchor{ServerName}
@deffn {Backend directive} ServerName "@var{name}"
This directive specifies the name to use for server name
identification (@dfn{SNI}).  It also rewrites the @code{Host:} header
for this particular backend.  This means you don't have to use
@code{SetHeader} in addition to it.
@end deffn

@node UseBackend
@subsubsection Globally Defined Backends
  The @code{Backend} section described above can also be used at the
topmost level of the configuration file.  Use this if you plan to use
same backend in several different services.

  When used globally the @code{Backend} keyword must always be
followed by the backend name in double-quotes.  The assigned name must
be unique among all global backends.

  To include a globally defined backend in a service, use
@code{UseBackend} or @code{Backend} keywords.

@deffn {Service directive} UseBackend "@var{name}"
Use globally-defined backend @var{name} in this service.  The backend
itself may be defined in global scope before or after the
@code{Service} section that uses it.
@end deffn

The @code{UseBackend} keyword adds the backend to the service exactly
as it was defined.  However, it may sometimes be necessary to alter
its priority and state.  To do so, use the @code{Backend} section.  If
the name argument specifies a globally-defined backend, the
@code{Backend} section can contain only the @code{Priority} and
@code{Disable} statements.

@node Special Backends
@subsubsection Special Backends
  Special backends are backends that don't rely on an external server
to handle the response, but instead are served by @command{pound}
itself.

@anchor{Error backend}
@deffn {Service directive} Error @var{status} [@var{file}]
Return a particular HTTP status.

The @var{status} argument supplies the HTTP status code to return.

Optional @var{file} argument is the name of a disk file with the error
page content.  If not supplied, the text is determined as usual: first
the @code{ErrorFile @var{status}} statement from the enclosing listener is
consulted.  If it is not present, the default error page is used.

This directive is useful in a catch-all service, which outputs an
error page if no service matching the incoming request was found.
@xref{Error responses}, for a discussion.
@end deffn

@deffn {Service directive} Redirect [@var{code}] "@var{url}"
Declares a special backend that responds to each request with a
redirect response.

Optional @var{code} can be one of: 301, 302 (the default), 303, 307,
or 308.

The @var{url} argument specifies the URL to redirect the request to.
Before use it is expanded as described in @ref{String Expansions}.

For compatibility with previous @command{pound} versions, if no
@samp{$@var{n}} references are found in @var{url}, the following logic
is used: if it is a "pure" host (i.e. with no path) then the client will be
redirected to that host, with the original request path appended. If
the @var{url} does contain a path (even if it is just a @samp{/}),
then the request path is ignored.

@xref{Redirects}, for a detailed discussion of this backend and its use.
@end deffn

@deffn {Service directive} Control
Defines a special backend that serves @dfn{pound management
interface}.  @xref{Service Control}, for a detailed discussion of this
feature.
@end deffn

@anchor{Metrics}
@deffn {Service directive} Metrics
This directive defines a special backend that generates Openmetric
telemetry output on the given URL.  Example usage:

@example
@group
Service
    URL "/metrics"
    Metrics
End
@end group
@end example

To control access to the telemetry endpoint, use the @code{ACL}
statement (@pxref{ACL}).

The @code{LogSuppress} directive (@pxref{LogSuppress}) is often used
in openmetric services to suppress logging of served HTTP requests:

@example
@group
Service
    URL "/metrics"
    Metrics
    ACL "secure"
    LogSuppress success
End
@end group
@end example

The metrics output is discussed in @ref{Metric Families}.
@end deffn

@anchor{Emergency}
@deffn {Service directive} Emergency ... End
Defines an @dfn{emergency backend}, which will be used only if all
other backends become unavailable.  @xref{Backend}, for a discussion
of directives that can be used within @code{Emergency} section.

If multiple @code{Emergency} sections are defined, an emergency
backend to use will be selected using the usual balancing technique
(@pxref{Balancer}).
@end deffn

@node Session
@subsection Session

@deffn {Service directive} Session ... End
Defines how a service deals with possible HTTP sessions.  Once a
session is identified, @command{pound} will attempt to send all
requests within that session to the same backend server.

@xref{Sessions}, for a detailed discussion of HTTP sessions and their
handling.
@end deffn

The following directives are available for use in @code{Session}
section.

@deffn {Session directive} Type @var{type}
Defines the expected type of sessions to handle.  Allowed values for
@var{type} are:

@table @code
@kwindex IP, session type
@item IP
A session is defined by the source IP.  All requests coming from the
same IP are considered to be in the same session.  The IP address is
defined by the @code{ID} statement (see below).

@kwindex BASIC, session type
@item BASIC
A session is defined by the @code{Authentication} HTTP header.  If the
header is present, and specifies the @samp{Basic} authentication type,
user ID is extracted from it.

@kwindex URL, session type
@item URL
A session is identified by the value of a particular query parameter.
The name of the parameter is given by the @code{ID} statement.

@kwindex PARAM, session type
@item PARM
Sessions are identified by HTTP parameter - a string that appears
after a semicolon in the URL, such as @samp{bar} in
@indicateurl{http://foo.com;bar}.

@kwindex COOKIE, session type
@item COOKIE
Sessions are identified by the value of an HTTP cookie, whose name is
given by the @code{ID} directive.

@kwindex HEADER, session type
@item HEADER
Sessions are identified by the value of HTTP header whose name is
given by the @code{ID} directive.
@end table
@end deffn

@deffn {Session directive} ID "@var{name}"
Specifies the @dfn{session identifier}: IP address (for @code{Type
IP}), query parameter name (for @code{Type URL}), cookie name (for
@code{Type COOKIE}), or header name (for @code{Type HEADER}).
@end deffn

@deffn {Session directive} TTL @var{n}
How long can a session be idle (in seconds). A session that has been idle for
longer than the specified number of seconds will be discarded.
This directive is mandatory.
@end deffn

@node Other Statements
@subsection Other Statements

@deffn {Service directive} Disabled @var{bool}
If @code{true}, mark this service as disabled.  Disabled services are
not used for request processing.  A service can be enabled or disabled
at runtime using the @command{poundctl} utility
(@pxref{poundctl commands, enable}).
@end deffn

@deffn {Service directive} Balancer @var{algo}
Sets the request balancing algorithm to use.  Allowed values for
@var{algo} are:

@table @asis
@item random
Use weighted random balancing algorithm.

@item iwrr
Use interleaved weighted round robin balancing.
@end table

@xref{Balancer}, for a detailed discussion of these algorithms.

This statement overrides the global @code{Balancer} statement
(@pxref{Global directives, Balancer}).
@end deffn

@deffn {Service directive} IgnoreCase @var{bool}
Ignore case when doing regex matching (default: @samp{false}).  This
directive sets the default for the following service matching
directives: @code{URL}, @code{Path}, @code{QueryParam}, @code{Query},
@code{StringMatch}, as well as for the @code{DeleteHeader}
modification directive.

This statement is deprecated and will be removed in future versions.
Please, use the @option{-icase} option to the matching directive
instead (@pxref{conditional-option}).
@end deffn

@node resolver
@section Resolver
@kwindex Resolver
  The @code{Resolver} section controls DNS lookups for dynamic backend
generation (@pxref{Dynamic backends}).  It can contain the following
directives:

@deffn {Resolver} CNAMEChain @var{n}
@cindex CNAME chains
Maximum allowed length of a @dfn{CNAME chain}.  CNAME chains are
formed by DNS CNAME records pointing to another CNAME.  Although
prohibited by the RFC, such usage occurs sometimes in the wild.
By default, @command{pound} does not accept CNAME chains.  If you work
with nameservers that declare such chains, set this statement to a
small integer value, defining maximum number of CNAME records in the
chain that @command{pound} will accept.  The value of 2 or 3 should
suffice in most cases.
@end deffn

@deffn {Resolver} ConfigFile @var{file}
@findex resolv.conf
Read resolver configuration from @var{file}.  Default is
@file{/etc/resolv.conf}.
@end deffn

@deffn {Resolver} ConfigText ... End
The material within this section is read verbatim and used as the
content of the resolver configuration file.  E.g.:

@example
@group
Resolver
        ConfigText
                domain example.org
                nameserver 192.0.2.1
                nameserver 192.0.2.4
        End
End
@end group
@end example

If both @code{ConfigFile} and @code{ConfigText} are used, the last
statement used wins.
@end deffn

@deffn {Resolver} Debug @var{bool}
If set to @code{true}, enables DNS debugging info.
@end deffn

@deffn {Resolver} RetryInterval @var{n}
Interval in seconds, after which to retry failed DNS queries or
queries that returned no RRs.  This value is used unless the backend
defines its own retry interval value.
@end deffn

@node poundctl
@chapter poundctl
  The @command{poundctl} command displays status of various objects of
the running instance and allows you to change some of them.

  The program communicates with the running @command{pound} daemon via
a UNIX socket or remotely, via HTTP or HTTPS.  The URL of the
communication socket can be given explicitly by the @option{-s}
command line option, or obtained from @command{poundctl} or
@command{pound} configuration files.

  If the @file{.poundctl} exists in the home directory, the
configuration will be obtained from it.  Otherwise, if
@command{poundctl} runs on the same machine as the @command{pound}
daemon and communicates with it via the UNIX socket, the program will
scan the @file{pound.cfg} file for the @code{Control} statement
(@pxref{Control statement}) and read the socket file name from it.
These ways of configuring @command{poundctl} are discussed below,
in @ref{poundctl config}.  In examples below, it is assumed that the
socket URL is obtained from one of configuration files.

  The program invocation syntax is:

@example
poundctl [@var{options}] @var{command} @var{object} [@var{arg}]
@end example

@noindent
Here, @var{options} are command line options, @var{command} is a
command verb that instructs @command{poundctl} what to do,
@var{object} identifies the @command{pound} object to operate upon
(@pxref{objects}), and optional @var{arg} supplies argument to the
command verb.

  Pound objects identifiers are formed in a path-like fashion:

@example
/@var{listener}/@var{service}/@var{backend}
@end example

@noindent
where:

@table @var
@item listener
Symbolic name of the listener or its ordinal number in the
configuration.  If referring to a globally-defined service, or to a
backend in such a service, a dash is used.

@item service
Symbolic name or ordinal number of the service located in that listener.

@item backend
Ordinal number of backend in the service.
@end table

Depending on the command, either @samp{/@var{backend}} or both
@samp{/@var{service}/@var{backend}} may be omitted.

For example, the following command will disable backend 2 in service 1 of
listener 0:

@example
poundctl disable /0/1/2
@end example

Assuming listener 0 is named @samp{web}, this example can also be
written as:

@example
poundctl disable /web/1/2
@end example

The following command disables the listener 0 itself:

@example
poundctl disable /0
@end example

A dash in place of @var{listener} refers to the global scope.  Thus,
the following disables service 1 defined in the global scope of
@file{pound.cfg}:

@example
poundctl disable /-/1
@end example

@menu
* poundctl commands::
* poundctl remote::
* poundctl config::
* poundctl options::
* poundctl template::
@end menu

@node poundctl commands
@section @command{poundctl} commands

@deffn {poundctl} list /@var{L}/@var{S}/@var{B}
@deffnx {poundctl} list /@var{L}/@var{S}
@deffnx {poundctl} list /@var{L}
@deffnx {poundctl} list
@anchor{poundctl list}
Lists status of the given object and its subordinates.  Without
argument, shows all listeners and underlying objects.
@end deffn

@deffn {poundctl} enable /@var{L}/@var{S}/@var{B}
@deffnx {poundctl} enable /@var{L}/@var{S}
@deffnx {poundctl} enable /@var{L}
@deffnx {poundctl} on /@var{L}/@var{S}/@var{B}
@deffnx {poundctl} on /@var{L}/@var{S}
@deffnx {poundctl} on /@var{L}
Enables listener, service, or backend.
@end deffn

@deffn {poundctl} disable /@var{L}/@var{S}/@var{B}
@deffnx {poundctl} disable /@var{L}/@var{S}
@deffnx {poundctl} disable /@var{L}
@deffnx {poundctl} off /@var{L}/@var{S}/@var{B}
@deffnx {poundctl} off /@var{L}/@var{S}
@deffnx {poundctl} off /@var{L}
Disables listener, service, or backend.
@end deffn

@deffn {poundctl} delete /@var{L}/@var{S} @var{key}
Delete the session with the given key.  Notice that backend may not
be specified.
@end deffn

@deffn {poundctl} add /@var{L}/@var{S}/@var{B} @var{key}
Add a session with the given @var{key}.
@end deffn

@node poundctl remote
@section Using @command{poundctl} for remote access
  Starting from version 4.14, @command{pound} is able to provide its
management interface via HTTP (@pxref{Service Control}).  To use
remote management interface, supply its URL with the @option{-s}
command line option.  The URL syntax is:

@example
@var{scheme}://[@var{user}[:@var{password}]@@]@var{hostname}[:@var{port}][/@var{path}]
@end example

@noindent
where @samp{[]} denote optional parts.  Valid @var{scheme} values are
@samp{http} and @samp{https}.  Use @var{user} and @var{password} if
the interface is protected by basic authentication (@pxref{Authentication}).

When using @samp{https} protocol, you may need to supply the
@dfn{certificate authority} file using the @option{-C @var{file}}
option, where @var{file} is the name of the file in PEM format.  This
option can also take a directory name as its argument.  In this case
all PEM files from that directory will be loaded.

To disable peer certificate verification, use the @option{-k} option.

If @command{pound} configuration requires the client to send its
certificate for authentication (@xref{ClientCert}, or
@pxref{ClientCert conditional}), use the
@option{-K @var{file}} option to supply it.  Its argument, @var{file},
is the name of the file with the certificate and key in PEM format.

@node poundctl config
@section Configuring @command{poundctl}
@findex .poundctl
@kwindex POUNDCTL_CONF
  Upon startup, the program checks if the file @file{.poundctl} exists
in the user's home directory.  If so, it reads its configuration from
it.  The location of the configuration file can be changed using the
environment variable @env{POUNDCTL_CONF}.  If it is defined and has a
non-empty value, its value is taken as the alternative file name to
use.  It can be either absolute file name, or a file name relative to
the home directory.  Setting @env{POUNDCTL_CONF} to an empty value
disables reading the configuration.

  If the program cannot determine the socket URL from
@file{.poundctl}, it will attempt to scan @command{pound}
configuration file, on the assumption that it runs on the same machine
as the daemon and that its @file{pound.cfg} file contains a
@code{Control} statement (@pxref{Control statement}).  If so, the
socket name is determined from it.

  Otherwise, the control URL has to be given explicitly using the
@option{-s} command line option.

  The @file{.poundctl} file has the same syntax as @file{pound.cfg}:
it is a sequence of @dfn{statements} and @dfn{sections}, separated by
arbitrary amount of empty lines and comments.  A @dfn{simple
statement} occupies a single line and consists of a keyword
(@dfn{directive}) and one or more values separated by whitespace.  A
@dfn{section} is a compound statement that encloses other statements
and sections.  Sections begin with a keyword, optionally followed by
arguments, and end with a word @code{End} on a line by itself.  All
keywords are case-insensitive.

The following keywords are available in the global scope:

@deffn {poundctl config} URL "@var{url}"
Sets the URL of the @command{pound} management socket.  The value is
either the file name of the UNIX socket file, or a remote URL, as
described in @ref{poundctl remote}.
@end deffn

@deffn {poundctl config} CAFile "@var{file}"
Name of the certificate authority file.  See also the @option{-C}
option, below.
@end deffn

@deffn {poundctl config} CAPath "@var{dir}"
Read certificate authority files from the directory @var{dir}.
@end deffn

@deffn {poundctl config} ClientCert "@var{file}"
Supplies the name of the file with client certificate and private key,
for client authentication.  See also the @option{-K} option, below.
@end deffn

@deffn {poundctl config} Verify @var{bool}
Enables or disables peer certificate verification.  The default is
@code{on}.  See also the @option{-k} command line option.
@end deffn

@deffn {poundctl config} TemplateFile "@var{file}"
Name of the template file (@pxref{poundctl template}).
@end deffn

@deffn {poundctl config} TemplatePath "@var{file}"
Search path for template files (@pxref{poundctl template}).
@end deffn

@deffn {poundctl config} TemplateName "@var{name}"
Name of the template to use (@pxref{poundctl template}).
@end deffn

@menu
* multiple servers::
@end menu

@node multiple servers
@subsection Multiple Servers Configuration
@kwindex Server, @command{poundctl} configuration
@kwindex -S, @command{poundctl} option
  The @code{Server} section provides a way to organize management
of multiple @command{pound} servers.  The idea is that you define
the configuration for each particular @command{pound} installation
in a separate @code{Server} section, and then use the name of that
section to identify the server of interest in the command line, using
the @option{-S} option:

@example
poundctl -S web list
@end example

  The syntax of the @code{Server} section is:

@example
@group
Server "@var{name}"
  ...
End
@end group
@end example

@noindent
where @var{name} is a unique name assigned to that server.  It will be
used as argument to the @option{-S} option to identify it.  The
ellipsis denotes one or more of the following statements:

@deffn {poundctl Server} URL @var{url}
Sets the URL of the @command{pound} management socket for that server.
The value is either the file name of the UNIX socket file, or a remote
URL, as described in @ref{poundctl remote}.
@end deffn

@deffn {poundctl Server} CAFile @var{file}
Name of the certificate authority file.
@end deffn

@deffn {poundctl Server} CAPath @var{dir}
Read certificate authority files from the directory @var{dir}.
@end deffn

@deffn {poundctl Server} ClientCert @var{file}
Supplies the name of the file with client certificate and private key,
for client authentication to that server.
@end deffn

@deffn {poundctl Server} Verify @var{bool}
Enables or disables peer certificate verification.  The default is
@code{on}.
@end deffn

@node poundctl options
@section @command{poundctl} options
  The following options are understood by @command{poundctl}:

@table @option
@kwindex -C, poundctl
@item -C @var{file}
@itemx -C @var{dir}
Read certificate authority files from @var{file} or from files in
@var{dir}.  @xref{poundctl remote}.  This overrides the @code{CAFile}
or @code{CAPath} configuration settings (@pxref{poundctl config}).

@kwindex -f, poundctl
@item -f @var{file}
Read @command{pound} configuration from @var{file}, instead of the
default configuration file.

@kwindex -i, poundctl
@item -i @var{n}
Sets indentation level for JSON output to @var{n} columns.

@kwindex -j, poundctl
@item -j
Use JSON output format.

@kwindex -K, poundctl
@item -K @var{file}
Read client certificate and private key from @var{file}.
@xref{poundctl remote}.  This option overrides the @code{ClientCert}
configuration setting (@pxref{poundctl config}).

@kwindex -k
@item -k
Disable peer certificate verification.  @xref{poundctl remote}.
This overrides the @code{Verify} configuration setting
(@pxref{poundctl config}).

@kwindex -h, poundctl
@item -h
Shows a short help output and exits.

@kwindex -S, poundctl
@item -S @var{name}
Operate on server defined by @code{Section "@var{name}"} in the
@file{.poundctl} file.  @xref{multiple servers}, for a detailed
discussion.

@kwindex -s, poundctl
@item -s @var{socket}
@itemx -s @var{url}
Sets pathname of the control socket, or its URL (for remote access,
@pxref{poundctl remote}).  This overrides the @code{URL} configuration
setting (@pxref{poundctl config}).

@kwindex -T, poundctl
@item -T @var{file}
Sets the name of the template file to use.  Overrides the
@code{TemplateFile} configuration setting (@pxref{poundctl config}).

@kwindex -t, poundctl
@item -t @var{name}
Defines the name of the template to use, instead of the
@samp{default}.  This overrides the @code{TemplateName} configuration
setting (@pxref{poundctl config}).

@kwindex -V, poundctl
@item -V
Prints program version, compilation settings, and exits.

@kwindex -v, poundctl
@item -v
Increases output verbosity level.
@end table

@node poundctl template
@section @command{poundctl} template
  Information received from the @command{pound} daemon is formatted as
a JSON object.  To produce human-readable output, @command{poundctl}
uses a @dfn{template}, i.e. a text written in a domain-specific
language expressly designed for that purpose.  The template language
complies, in general, with the specification in
@uref{https://pkg.go.dev/text/template}.  @xref{Template syntax},
for a detailed description.

@cindex poundctl.tmpl
@cindex template search path
@cindex search path, templates
Templates are stored in template files, which are looked up in the
template search path.  The path is a column-delimited list of
directories or file names.  To locate the template file, the
path is scanned left-to right.  If an element is a regular file name
(or a hard or symbolic link to a regular file), @command{poundctl}
tries to open that file.  If an element is a directory name,
the program tries to open the file @file{poundctl.tmpl}
in that directory.  If opening succeeds, further scanning stops and templates
are read from that file.

The default template path is

@example
~/.poundctl.tmpl:@var{datadir}/pound
@end example

@noindent
where @var{datadir} stands for the program data directory@footnote{It
is determined at compile time.  Normally it is @file{/usr/share/pound}
or @file{/usr/local/share/pound}.}.  That is, the file
@file{.poundctl.tmpl} in the user home directory is searched first,
then the file @file{poundctl.tmpl} (without the leading dot) is looked
up in the program data directory.

@kwindex POUND_TMPL_PATH
The default search path can be changed in the configuration file,
using the @code{TemplatePath} statement (@pxref{poundctl config}), or
by setting the environment variable @env{POUND_TMPL_PATH}.

To examine the default value of the search path, use the @option{-V}
command line option.

The template file to use can be requested from the command line using the
@option{-t} option (or @code{TemplateFile} configuration setting).  In
this case, template search path in not searched and the supplied file
is used verbatim.

Unless instructed otherwise, @command{poundctl} uses the template
@samp{default}.  You can request another template name using the
@code{TemplateName} configuration setting or the @option{-T} command
line option.

The default @file{poundctl.tmpl} file defines two templates:
@samp{default} and @samp{xml}.

@menu
* Template syntax::
* Pipelines::
* Variables::
* Input object::
@end menu

@node Template syntax
@subsection Template syntax
  The syntax of @command{poundctl} templates is modelled after and mostly
conforming to the specifications of the @command{golang} template
module@footnote{@url{https://pkg.go.dev/text/template}}.

Templates are executed by applying them to a JSON object.  Annotations
in a template refer to attributes of the object to control execution
and derive values to be displayed.  Execution of the template walks
the structure and sets the cursor, represented by a period (called
@dfn{dot}), to the value at the current location in the object as
execution proceeds.

The input text for a template is as ASCII text is arbitrary format.

Actions (data evaluations or control structures) are delimited by
@samp{@{@{} and @samp{@}@}}; all text outside actions is copied to the
output verbatim.

To aid in formatting template source code, if @samp{@{@{} is followed
immediately by a minus sign and white space, all trailing white space
is trimmed from the immediately preceding text.  Similarly, if
@samp{@}@}} is preceded by white space and a minus sign, all leading
white space is trimmed from the immediately following text.  Notice that the
presence of the whitespace in these trim markers is mandatory:
@samp{@{@{- 3@}@}} trims the immediately preceding text and outputs
@samp{3}, while "@samp{@{@{-3@}@}} parses as an action containing the
number @samp{-3}.

@menu
* Actions::
* Arguments::
@end menu

@node Actions
@subsubsection Actions
Here is the list of actions.  @dfn{Arguments} and @dfn{pipelines}
are evaluations of data, defined in detail in the sections that follow.

@table @code
@item @{@{ @}@}
Empty action is discarded.  It may be useful to trim the preceding or
following whitespace, as in

@example
@{@{- -@}@}
@end example

@item @{@{/* a comment */@}@}
Comments are discarded.  They may span multiple lines of text.
Comments do not nest and must start immediately after the opening
delimiter (with optional dash and whitespace in between).  A comment
may be followed by any action described below.

Comments may be used to control trailing and leading whitespace as
well:

@example
@{@{- a comment trimming the surrounding whitespace -@}@}
@end example

@item @{@{ @var{pipeline} @}@}
The @var{pipeline} is evaluated, and the default textual
representation of its value is copied to the output.

@item @{@{if @var{pipeline} @}@} @var{T1} @{@{end@}@}
If the value of the @var{pipeline} is empty, no output is generated;
otherwise, @var{T1} is executed.  The empty values are @code{null},
@code{false}, numeric 0, empty string (@samp{""}),
array (@samp{[]}), or object (@samp{@{@}}).  Dot is unaffected.

@item @{@{if @var{pipeline} @}@} @var{T1} @{@{else@}@} @var{T0} @{@{end@}@}
If the value of the pipeline is empty, @var{T0} is executed;
otherwise, @var{T1} is executed. Dot is unaffected.

@item @{@{if @var{pipeline} @}@} @var{T1} @{@{else if @var{pipeline} @}@} @var{T2} @{@{else@}@} @var{T0} @{@{end@}@}
A shortcut to simplify writing the if-else chains.  Equivalent to
(newlines added for readability):

@example
@group
@{@{if @var{pipeline} @}@}
  T1
@{@{else -@}@}
 @{@{if @var{pipeline} @}@}
   T2
 @{@{else@}@}
   T0
 @{@{end@}@}
@{@{end@}@}
@end group
@end example

@item @{@{range @var{pipeline} @}@} @var{T1} @{@{end@}@}
The value of @var{pipeline} must be an object or array.  If it is of
length zero, nothing is output.  Otherwise, dot is set to the
successive elements of the array or object and @var{T1}
is executed.  For objects, the elements will be	visited in sorted key
order.

@item @{@{range @var{pipeline} @}@} @var{T1} @{@{else@}@} @var{T0} @{@{end@}@}
Same as above, except that if the value of the @var{pipeline} is of
length zero, @var{T0} is executed with dot unaffected.

Within the @code{@{@{range@}@}} action, the following two keywords may
appear:

@table @code
@item @{@{break@}@}
The innermost @samp{@{@{range @var{pipeline}@}@}} loop is ended early,
stopping the current iteration and bypassing all remaining iterations.

@item @{@{continue@}@}
The current iteration of the innermost @samp{@{@{range @var{pipeline}@}@}}
loop is stopped, and the loop starts the next iteration.
@end table

@item @{@{define "@var{name}"@}@} @var{text} @{@{end@}@}
The @var{text} is collected and stored for the further use as template
with the given @var{name}.  It can be invoked using the
@samp{@{@{template@}@}} action (see below).

@item @{@{template "@var{name}"@}@}
The template with the specified @var{name} (see the @samp{@{@{define@}@}}
above) is executed with dot set to @code{null}.

@item @{@{template "@var{name}" @var{value} @}@}
The template with the specified @var{name} (see the @samp{@{@{define@}@}}
above) is executed with dot set to @var{value}.

@item @{@{block "@var{name}" @var{pipeline} @}@} @var{T1} @{@{end@}@}
A block is shorthand for defining a template and then executing it in
place:

@example
@{@{define "@var{name}"@}@} @var{T1} @{@{end@}@}
@{@{template "@var{name}" @var{pipeline}@}@}
@end example

@item @{@{with @var{pipeline} @}@} @var{T1} @{@{end@}@}
If the value of the @var{pipeline} is empty, no output is generated;
otherwise, dot is set to the value of the @var{pipeline} and @var{T1} is
executed.

@item @{@{with @var{pipeline} @}@} @var{T1} @{@{else@}@} @var{T0} @{@{end@}@}
Same as above, but if the value of the @var{pipeline} is empty,
@var{T0} is executed with dot unchanged.
@end table

@node Arguments
@subsubsection Arguments
An @dfn{argument} is a simple value, i.e. any of the following:

@itemize @bullet
@item Numeric value (integer or floating point)
@item Boolean value: @code{true} or @code{false}.
@item Quoted string.
@item A dot (@samp{.})
This represents the cursor value.
@item Attribute: @samp{.@var{attr}}
This is the value of the attribute @var{attr} in the current value
(dot).
Attribute references can be nested, as in @samp{.Attr.Xattr.Yattr}.
@item A variable reference: @samp{$@var{var}}.
Here, @var{var} is the name of the variable defined in the @code{range}
action.  @xref{Variables}, below.

@item Function call in parentheses, for grouping.
@end itemize

@node Pipelines
@subsection Pipelines
  A @dfn{pipeline} is a series of one or more @dfn{commands} delimited
by pipe sign (@samp{|}).  Each @dfn{command} is either an argument or
a @dfn{function call}, in form:

@example
@var{func} @var{arg1} @var{arg2}...
@end example

@noindent
where @var{func} is the name of one of the built-in functions
discussed below.

Pipelines are executed from left to right, with the result of the
previous command implicitly added to the list of arguments of each
subsequent command.  For example, the pipeline

@example
.attr | eq $x
@end example

@noindent
is equivalent to

@example
eq $x .attr
@end example

@noindent
i.e. it calls the built-in function @code{eq} with two arguments: the
value of the variable @samp{x} and attribute @samp{attr} of the cursor
value.

The following built-in functions are defined:

@deffn {Template built-in} and A1 A2
Evaluates to @code{true} if pipelines @var{A1} and @var{A2} both
evaluate to @code{true}.  Notice, that there is no boolean shortcut
evaluation: both pipelines are evaluated prior to calling @code{and}.
@end deffn

@deffn {Template built-in} or A1 A2
Evaluates to @code{true} if at least one of the pipelines @var{A1} and
@var{A2} evaluates to @code{true}.  Notice, that there is no boolean
shortcut evaluation: both pipelines are evaluated prior to calling @code{or}.
@end deffn

@deffn {Template built-in} index A1 A2...
Returns the result of indexing its first argument by the following
arguments.  Thus, if @samp{.} is an array, then:

@example
index . 5
@end example

@noindent
evaluates to its fifth element (@samp{.[5]}).
@end deffn

@deffn {Template built-in} len A1
Returns the integer length of its argument.
@end deffn

@deffn {Template built-in} not A1
Returns @code{true} if its argument evaluates to @code{false}.
@end deffn

@deffn {Template built-in} eq A1 A2
Returns @code{true} if both its arguments are equal.  This applies only
if both @var{A1} and @var{A2} are numeric or if they both are strings.
@end deffn

@deffn {Template built-in} ne A1 A2
Returns @code{true} if its arguments (both must be numeric or strings)
are not equal.
@end deffn

@deffn {Template built-in} lt A1 A2
Returns @code{true} if @var{A1} is numerically less than @var{A2}.
@end deffn

@deffn {Template built-in} le A1 A2
Returns @code{true} if @var{A1} is numerically less than or equal to @var{A2}.
@end deffn

@deffn {Template built-in} gt A1 A2
Returns @code{true} if @var{A1} is numerically greater than @var{A2}.
@end deffn

@deffn {Template built-in} ge A1 A2
Returns @code{true} if @var{A1} is numerically greater than or equal
to @var{A2}.
@end deffn

@deffn {Template built-in} even A1
Returns @code{true} if @var{A1}, which must evaluate to an integer
value, is divisible by 2.
@end deffn

@deffn {Template built-in} printf FMT A1...
Implements the @code{printf} function.  @var{FMT} must evaluate to
string.  Rest of arguments is interpreted according to the conversion
specifications in @var{FMT}.  The result is a formatted string.

In addition to the standard conversion specifications, the @samp{%v}
specifier is implemented: it formats its argument in the best
way, depending on its actual type.
@end deffn

@deffn {Template built-in} typeof A1
Evaluates to the type of its argument, one of:
@code{null}, @code{bool}, @code{number}, @code{integer}, @code{string},
@code{array}, and @code{object}.
@end deffn

@deffn {Template built-in} exists A1 A2
@var{A1} must evaluate to an object and @var{A2} to string.  The
function evaluates to @code{true} if the attribute @var{A2} is present
in @var{A1}.
@end deffn

@deffn {Template built-in} add A1 A2...
Returns the sum of its arguments.
@end deffn

@deffn {Template built-in} sub A1 A2
Returns the difference @code{@var{A1} - @var{A2}}.
@end deffn

@deffn {Template built-in} mul A1 A2
Multiplies @var{A1} by @var{A2}.
@end deffn

@deffn {Template built-in} div A1 A2
Divides @var{A1} by @var{A2}.
@end deffn

@node Variables
@subsection Variables
 Variables (referred to as @code{$@var{name}}) can be defined in
@code{range} and @code{with} actions.  For @code{range}, the syntax is:

@example
@{@{range $@var{index}, $@var{element} = @var{pipeline} @}@} @var{T1} @{@{end@}@}
@end example

@noindent
where @var{index} and @var{element} are arbitrary variable names.
When executing this action, during each iteration @var{$index} and
@var{$element} are set to the index (attribute name) and value of
each successive element.  Dot remains unaffected.

For @code{with}, the syntax is:

@example
@{@{with $@var{var} = @var{pipeline} @}@} @var{T1} @{@{end@}@}
@end example

@var{Pipeline} is evaluated, its result is assigned to @var{$var} and
the @var{T1} block is executed with dot unchanged.

A variable's scope extends to the @code{end} action of the control
structure (@code{with} or @code{range}) in which it is declared.  This
includes any nested statements that may appear in between.

@node Input object
@subsection Input object
Depending on the request issued by @command{poundctl}, the invoked template
can receive as its argument (@dfn{dot}) an object of the following
types: @dfn{full listing}, @dfn{listener}, @dfn{service}, or @dfn{backend}.

Since there is no explicit indication of the object type being passed,
templates normally use heuristics based on the presence or absence of
certain attribute to deduce the object type in question.  The
recommended approach is described in the following pseudo-code
fragment:

@example
@group
@{@{if exists . "listeners" @}@}
  @{@{/* This is a full listing, as requested by @command{poundctl list}. */@}@}
  ...
@{@{else if exists . "services"@}@}
  @{@{/* Single listener, as requested by @command{poundctl list /@var{L}}.
       Notice that this attribute is present in the full listing as
       well, so presence of "listeners" should be checked first. */@}@}
  ...
@{@{else if exists . "backends"@}@}
  @{@{/* Single service, as requested by @command{poundctl list /@var{L}/@var{S}}. */@}@}
  ...
@{@{else@}@}
  @{@{/* Backend listing (@command{poundctl list /@var{L}/@var{I}/@var{B}}) */@}@}
  ...
@{@{end@}@}
@end group
@end example

Structures of each object are discussed in subsections that follow.

@menu
* Full listing::
* Listener object::
* Service object::
* Backend object::
@end menu

@node Full listing
@subsubsection Full listing
A full listing contains the following attributes:

@table @code
@item listeners
An array of @dfn{listener} objects.  See below for a description.

@item services
An array of @dfn{service} objects, representing services defined in
the global scope of the @command{pound} configuration file.

@item pid
PID of the running @command{pound} daemon.

@item version
@command{Pound} version number (string).

@item workers
Workers statistics.  This is a JSON object with the following
attributes:

@table @code
@item active
Number of active threads.

@item count
Number of threads currently running.

@item max
Maximum number of threads.

@item min
Minimum number of threads.

@item timeout
Thread idle timeout.
@end table

@item queue_len
Number of incoming HTTP requests in the queue (integer).

@item timestamp
Current time on the server, formatted as ISO 8601 date-time with
microsecond precision, e.g.: @samp{2023-01-05T22:43:18.071559}.
@end table

@node Listener object
@subsubsection Listener
A @dfn{listener} object represents a single HTTP or HTTPS listener in
@command{pound} configuration.  It has the following attributes:

@table @code
@item address
Address of this listener.  A string formatted as @samp{@var{ip}:@var{port}}.
for IPv4 and IPv6 addresses or containing a socket file name, for UNIX
sockets.

@item protocol
Protocol used: either @samp{http} or @samp{https}.

@item services
Array of @dfn{service} objects representing services defined in this
listener.  See below for the definition of a @dfn{service} object.

@item enabled
Boolean. Whether this listener is enabled or not.

@item nohttps11
Value of the @code{NoHTTPS11} configuration statement for this
listener (@pxref{ListenHTTPS, NoHTTPS11}).  One of: 0, 1, 2.
@end table

@node Service object
@subsubsection Service
  A @dfn{service} object describes a single service.

@table @code
@item name
Symbolic name of this service.

@item enabled
Boolean.  Whether this service is enabled or not.

@item session_type
Name of the session handling algorithm for this service.  One of:
@samp{IP}, @samp{BASIC}, @samp{URL}, @samp{PARM}, @samp{COOKIE},
@samp{HEADER}.

@item sessions
List of active sessions in this service.  Each session is represented
as object with the following attributes:

@table @code
@item key
Session key (string).

@item backend
Ordinal number of the backend assigned to handle requests with this session.

@item expire
Expiration time of this session, formatted as
@samp{1970-01-01T00:00:00.000000} (with microsecond precision).
@end table

@item backends
List of @dfn{backends} defined for this service.

@item emergency
Emergency @dfn{backend} object, or @code{null} if no such backend is
defined.
@end table

@node Backend object
@subsubsection Backend
The following attributes are always present in each @dfn{backend} object:

@table @code
@item alive
Whether or not this backend is alive.

@item conn_to
Connection timeout for this backend (seconds).

@item enabled
Whether or not this backend is enabled.

@item io_to
I/O timeout for this backend (seconds).

@item priority
Priority value assigned to this backend.

@item protocol
Protocol used by this backend: either @samp{http} or @samp{https}.

@item type
Backend type.  One of: @samp{acme}, @samp{backend}, @samp{control},
@samp{redirect}.

@item ws_to
Websocket timeout (seconds).
@end table

Depending on the backend type, the following attributes may be
present:

@table @code
@item acme
An object of the following structure:

@table @code
@item path
Directory where ACME challenges are stored.
@end table

@item backend
Object:
@table @code
@item address
Backend address.
@end table

@item redirect
Object:
@table @code
@item url
URL to redirect to.
@item code
HTTP code for redirection responses.  One of: 301, 302, 307.
@item redir_req
Boolean: whether to append the original request path to the resulting location.
@end table
@end table

If backend statistics is enabled (@pxref{BackendStats}),
the @code{stats} object will be present, with the following attributes:

@table @code
@item request_count
Total number of requests processed by this backend.
@item request_time_avg
Average time per request, in nanoseconds.
@item request_time_stddev
Standard deviation of the above.
@end table

@node Metric Families
@appendix Metric Families
@include metrics.texi

@node Time and Date Formats
@appendix Time and Date Formats
@include strftime.texi

@node GNU Free Documentation License
@appendix GNU Free Documentation License

@include fdl.texi

@node Index
@unnumbered Index
@printindex cp

@ifset WEBDOC
@ifhtml
@node This Manual in Other Formats
@unnumbered This Manual in Other Formats
@include otherdoc.texi
@end ifhtml
@end ifset

@bye
