NGINX for the Developer
[ 176 ]
Decision-making in NGINX
You may find yourself trying to bend NGINX's configuration directives in ways that
they were not meant to be used. This is frequently seen in configurations where there
are a lot of if checks to try to emulate some sort of logic chain. A better option would
be to use NGINX's embedded perl module. With this module, you will be able to use
the flexibility of Perl to achieve your configuration goals.
The perl module is not built by default, so it needs to be enabled with the --with-
http_perl_module configure switch. Ensure as well that your Perl was built with
-Dusemultiplicity=yes (or -Dusethreads=yes) and -Dusemymalloc=no. NGINX
configuration reloads will cause the perl module to leak memory over time, so this
last parameter is included to help mitigate that problem.
After having built an nginx with embedded Perl, the following directives
are available:
Table: Perl module directives
Directives Explanation
perl Activates a Perl handler for this location. The
argument is the name of the handler or a string
describing a full subroutine.
perl_modules Specifies an additional search path for Perl
modules.
perl_require Indicates a Perl module that will be loaded at
each NGINX reconfiguration. May be specified
multiple times for separate modules.
perl_set Installs a Perl handler to set the value of a
variable. The argument is the name of the
handler or a string describing a full subroutine.
When writing Perl scripts to be used in an NGINX configuration, you have use of
the $r object, representing the request. The methods on this object are as follows:
- $r->args: The request arguments.
- $r->filename: The name of the file referenced by the URI.
- $r->has_request_body(handler): If there is a request body, the handler
will be called. - $r->allow_ranges: Enables the use of byte ranges in a response.
- $r->discard_request_body: Discards the body of the request.