41,99 €
An in-depth guide to configuring NGINX for your everyday server needs
This book is for system administrators and engineers who want to personalize NGINX, and design a robust configuration module to solve their hosting problems. Some knowledge of NGINX is a plus, but is not a prerequisite.
NGINX is a high-performance HTTP server and mail proxy designed to use very few system resources. But despite its power it is often a challenge to properly configure NGINX to meet your expectations. Mastering Nginx is the solution – an insider's guide that will clarify the murky waters of NGINX's configuration. Tune NGINX for various situations, improve your NGINX experience with some of the more obscure configuration directives, and discover how to design and personalize a configuration to match your needs.
To begin with, quickly brush up on installing and setting up the NGINX server on the OS and its integration with third-party modules. From here, move on to explain NGINX's mail proxy module and its authentication, and reverse proxy to solve scaling issues. Then see how to integrate NGINX with your applications to perform tasks.
The latter part of the book focuses on working through techniques to solve common web issues and the know-hows using NGINX modules. Finally, we will also explore different configurations that will help you troubleshoot NGINX server and assist with performance tuning.
This is a mastering guide where you will follow an instructional, conversational approach working through problems and their solutions.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 367
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2013
Second edition: July 2016
Production reference: 1220716
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78217-331-1
www.packtpub.com
Author
Dimitri Aivaliotis
Reviewer
Markus Jelsma
Acquisition Editor
Kevin Colaco
Content Development Editor
Rashmi Suvarna
Technical Editors
Naveenkumar Jain
Novina Kewalramani
Copy Editor
Vikrant Phadke
Project Coordinator
Judie Jose
Proofreader
Safis Editing
Indexer
Hemangini Bari
Graphics
Kirk D'Penha
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
Dimitri Aivaliotis is a production engineer in Silicon Valley. His career has taken him from building a Linux-based computer network for a school up through multi-datacenter, high-availability infrastructures for banks and popular websites. He has spent over a decade solving his customers' problems and learned NGINX along the way.
Dimitri graduated summa cum laude with a BS in Physics from Rensselaer Polytechnic Institute and received an MS in Management Information Systems at Florida State University.
One would think that a second edition should be easy to write, correcting the errors of the first and updating the content. On the one hand, there is much less to write from scratch, but on the other hand, everything must be re-evaluated. It's not as easy as it may seem at first.
I'd like to thank all the reviewers for keeping me honest and pointing out where things are not clear. Any remaining errors are, of course, my own.
Thank you Packt for giving me this opportunity to have another go at writing this book.
Thank you Nginx Inc. for creating a product so flexible and performant that it's still in wide use today.
Markus Jelsma is the CTO and co-owner of Openindex B.V, a Dutch company specializing in open source search and crawl solutions. As a committer and PMC member of Apache Nutch, he's an expert in search engine technology and web crawling solutions.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
For Katja. You mean the world to me.
NGINX is a high-performance web server designed to use very few system resources. There are many how-to guides and example configurations floating around the Web. This guide will serve to clarify the murky waters of NGINX configuration. In doing so, you will learn how to tune NGINX for various situations, what some of the more obscure configuration options do, and how to design a decent configuration to match your needs.
You will no longer feel the need to copy-paste a configuration snippet because you will understand how to construct a configuration file to do exactly what you want it to do. This is a process and there will be bumps along the way, but with the tips explained in this book, you will feel comfortable writing an NGINX configuration file by hand. In case something doesn't work as expected, you will be able to debug the problem yourself, or at least be capable of asking for help without feeling like you haven't given it a try yourself.
This book is written in a modular fashion. It is laid out to help you get to the information you need as quickly as possible. Each chapter is pretty much a standalone piece. Feel free to jump in anywhere you feel you need to get more in-depth about a particular topic. If you feel you have missed something major, go back and read the earlier chapters. They are constructed in a way to help you grow your configuration piece by piece.
Chapter 1, Installing NGINX and Third-Party Modules, teaches you how to install NGINX on your operating system of choice and how to include third-party modules in your installation.
Chapter 2, A Configuration Guide, explains the NGINX configuration file format. You will learn what each of the different contexts is for, how to configure global parameters, and what a location is used for.
Chapter 3, Using the mail Module, explores NGINX's mail proxy module, detailing all aspects of its configuration. An example authentication service is included in the code for this chapter.
Chapter 4, NGINX as a Reverse Proxy, introduces the concept of a reverse proxy and describes how NGINX fills that role.
Chapter 5, Reverse Proxy Advanced Topics, delves deeper into using NGINX as a reverse proxy to solve scaling issues and performance problems.
Chapter 6, The NGINX HTTP Server, describes how to use the various modules included with NGINX to solve common webserving problems.
Chapter 7, NGINX for the Application Developer, shows how NGINX can be integrated with your application to deliver content to your users more quickly.
Chapter 8, Integrating Lua with NGINX, provides a brief look at how to extend NGINX functionality using the embedded Lua scripting language.
Chapter 9, Troubleshooting Techniques, investigates some common configuration problems, how to debug a problem once it arises, and makes some suggestions for performance tuning.
Appendix A, Directive Reference, provides a handy reference for the configuration directives used throughout the book, as well as a selection of others not previously covered.
Appendix B, The Rewrite Rule Guide, describes how to use the NGINX rewrite module and describes a few simple steps for converting Apache-style rewrite rules into ones NGINX can process.
Appendix C, The NGINX Community, introduces you to the online resources available to seek more information.
Appendix D, Persisting Solaris Network Tunings, details what is necessary to persist different network tuning changes under Solaris 10 and above.
Any modern Linux PC should be sufficient to run the code samples in the book. The installation instructions are given in each chapter that uses code samples. Basically, it boils down to:
You are an experienced systems administrator or systems engineer, familiar with installing and configuring servers to meet specific needs. You do not need experience using NGINX.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "This section will be placed at the top of the nginx.conf configuration file."
A block of code is set as follows:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/Bookname_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
NGINX was first conceived to be an HTTP server. It was created to solve the C10K problem, described by Daniel Kegel on http://www.kegel.com/c10k.html, in designing a web server to handle 10,000 simultaneous connections. NGINX can do this through its event-based connection-handling mechanism and will use the OS-appropriate event mechanism in order to achieve this goal.
Before we begin exploring how to configure NGINX, we will first install it. This chapter details how to install NGINX and how to get the correct modules installed and configured. NGINX is modular by design and there is a rich community of third-party module developers who have added functionality to the core NGINX server by creating modules that can be compiled into the server and installed along with it.
In this chapter, we will cover the following topics:
Chances are that your operating system of choice already provides nginx as a package. Installing it is as simple as using your package manager's commands:
The sudo command is representative of what you need to execute on your operating system to achieve superuser (root) privileges. If your operating system supports role-based access control (RBAC), then you would use a different command, such as pfexec, to achieve the same goal.
These commands will install NGINX into standard locations, specific to your operating system. This is the preferred installation method if you need to use your operating system's packages.
The NGINX core team also provides binaries of the stable version, available from http://nginx.org/en/download.html. Users of distributions without an nginx package (such as CentOS) can use the following instructions to install pre-tested and pre-compiled binaries.
Add the NGINX repository to your yum configuration by creating the following file:
Then install nginx by executing the following command:
Alternative instructions for installing an nginx-release package are available at the preceding URL.
Let's install NGINX on Debian using the following steps:
If your operating system does not include nginx in its list of available packages, the version is too old for what you would like to do, the packages at nginx.org don't serve your needs, you would like to use the development release of NGINX, or if you want to enable/disable specific modules, then compiling NGINX from source is the only other option.
NGINX downloads are available for two separate branches of NGINX code—mainline and stable. The mainline branch is the one in which active development is taking place. Here is where new features will be found and integrated before finding their way into the stable branch. When a mainline version is released, it has undergone the same QA and a similar set of functional tests as the stable branch, so either branch may be used on production systems. The major difference between the two branches lies in the support of third-party modules. The internal API may change in the mainline release, whereas it stays the same on the stable branch, so backward compatibility for third-party modules is only available for stable releases.
In order to compile NGINX from source, certain requirements need to be met on your system. Besides a compiler, you also need the OpenSSL and Perl Compatible Regular Expressions (PCRE) libraries and development headers if you want to enable SSL support and be able to use the rewrite module, respectively. The rewrite module is enabled by default, so if you don't have PCRE libraries and headers, you'll need to disable the rewrite module during the configuration phase. Depending on your system, these requirements may already be met in the default installation. If not, you will need to both locate the appropriate package and install it, or download the source, unpack it, and point NGINX's configure script to this location.
NGINX will attempt to build a dependent library statically if you include a --with-<library>=<path> option to configure. You might do this if you want to ensure that NGINX is not dependent on any other part of the system and/or would like to squeeze that extra bit of performance out of your nginx binary. If you are using features of external libraries that are only available from a certain version onwards (for example, the next protocol negotiation TLS extension available from OpenSSL Version 1.0.1), then you have to specify the path to the unpacked sources of that particular version.
There are other, optional, packages that you can provide support for, if you like. These include MD5 and SHA-1 hashing algorithm support, zlib compression, and libatomic library support. The hashing algorithms are used in many places in NGINX, for example, to compute the hash of a URI to determine a cache key. The zlib compression library is used for delivering gzipped content. If the atomic_ops library is available, NGINX will use its atomic memory update operations to implement high-performance memory-locking code.
NGINX can be downloaded from http://nginx.org/en/download.html. Here you will find the source of either branch in .tar.gz, or .zip format. Unpack the archive into a temporary directory as follows:
Configure it using the following command:
And compile it as follows:
When compiling your own nginx binary, you are much more free to include only what you need. Can you already say under which user NGINX should run? Do you want to specify the default log file locations so that they don't need to be explicitly set in the configuration? The following table of configure options will help you design your own binary. These are options that are valid for NGINX, independent of which module is activated.
Option
Explanation
--prefix=<path>
The root of the installation. All other installation paths are relative to this one.
--sbin-path=<path>
The path to the nginx binary. If not specified, this will be relative to the prefix.
--conf-path=<path>
The path to where nginx will look for its configuration file, if not specified on the command line.
--error-log-path=<path>
This is where nginx will write its error logfile, unless configured otherwise.
--pid-path=<path>
This is where nginx will write the pid file of the master process, usually under /var/run.
--lock-path=<path>
The path to the shared memory mutex lock file.
--user=<user>
The user under which the worker processes should run.
--group=<group>
The group under which the worker processes should run.
--with-file-aio
Enables asynchronous I/O for FreeBSD 4.3+ and Linux 2.6.22+.
--with-debug
This option will enable debug logging. Not recommended for production systems.
You are also able to compile with optimizations that you may not get in a packaged installation. This is where the following options can be especially useful:
Option
Explanation
--with-cc=<path>
If you would like to set a C compiler that is not in your default PATH.
--with-cpp=<path>
This is the corresponding path to the C preprocessor.
--with-cc-opt=<options>
Here is where the path to the necessary include files may be indicated (-I<path>), as well as optimizations (-O4) and specifying a 64-bit build.
--with-ld-opt=<options>
The options to the linker include library path (-L<path>) and run path (-R<path>).
--with-cpu-opt=<cpu>
A build specific to a particular CPU family may be specified with this option.
NGINX is unique among high-performing web servers in that it was also designed to be a mail proxy server. Depending on your goals in building NGINX, you can configure it for web acceleration, a web server, a mail proxy, or all three. It may be beneficial to have one package that you can install on any server in your infrastructure and be able to set NGINX's role through configuration, or it may serve your needs better to have a slimmed-down binary to use in high-performance environments where every extra KB counts.
The following table specifies configuration options that are unique to the mail module.
Option
Explanation
--with-mail
This will enable the mail module, which is not activated by default.
--with-mail_ssl_module
In order to proxy any kind of mail transaction that uses SSL/TLS, this module will need to be activated.
--without-mail_pop3_module
When enabling the mail module, the POP3 module may be disabled separately.
--without-mail_imap_module
When enabling the mail module, the IMAP module may be disabled separately.
--without-mail_smtp_module
When enabling the mail module, the SMTP module may be disabled separately.
--without-http
This option will completely disable the http module; use it if you know you only want to compile in mail support.
For a typical mail proxy, I would recommend configuring NGINX as follows:
SSL/TLS is needed nowadays on almost every mail installation and not having it enabled on a mail proxy robs users of expected functionality. I've recommended compiling OpenSSL statically so that there are no dependencies on the operating system's OpenSSL library. This does mean, though, that you will have to be vigilant and ensure that your statically-compiled OpenSSL is kept up-to-date and rebuild your binary when necessary. The BUILD_DIR variable referenced in the preceding command would of course have to be set beforehand.
The following table shows what configuration options are available to the http module, from activating the Perl module to specifying the location of temporary directories.
Option
Explanation
--without-http-cache
When using the upstream module, NGINX can be configured to cache the contents locally. This option disables that cache.
--with-http_perl_module
NGINX configuration can be extended by using Perl code. This option activates that module. (Use of this module, however, degrades performance when blocking I/O is done.)
--with-perl_modules_path=<path>
This option specifies the path to additional Perl modules needed for using the embedded Perl interpreter. It may also be specified as a configuration option.
--with-perl=<path>
The path to Perl (Version 5.6.1 and higher), if not found on the default path.
--http-log-path=<path>
The default path to the HTTP access log.
--http-client-body-temp-path=<path>
When receiving the request from the client, this is the directory used as a temporary location for the body of that request. If the WebDAV module is enabled, it is recommended to set this path to be on the same filesystem as the final destination.
--http-proxy-temp-path=<path>
When proxying, this is the directory used as a location to store temporary files.
--http-fastcgi-temp-path=<path>
The location for FastCGI temporary files.
--http-uwsgi-temp-path=<path>
The location for uWSGI temporary files.
--http-scgi-temp-path=<path>
The location for SCGI temporary files.
NGINX uses the OpenSSL Project for TLS/SSL protocols. More information about this Open Source toolkit can be found at https://www.openssl.org. Support for SSL can be had from either the OS or directly from a separate copy of the toolkit. If you use either --with-http_ssl_module or --with-mail_ssl_module without --with-ssl, you're using the OpenSSL library that is installed on the machine where you executed the configure command. If you'd like to compile against a specific version of OpenSSL, download the distribution, unpack it in a directory, and then specify the path to that directory as the argument to --with-openssl. Use the --with-openssl-opt option to specify additional build options for OpenSSL itself.
For example, to build NGINX with an OpenSSL that has optimized elliptic curves, you would use a command such as the following:
Besides the http and mail modules, there are a number of other modules included in the NGINX distribution. These modules are not activated by default, but may be enabled by setting the appropriate configuration option:
Option
Explanation
--with-http_ssl_module
If you need to encrypt web traffic, you will need this option to be able to use URLs beginning with https. (Requires the OpenSSL library.)
--with-http_realip_module
If your NGINX is behind an L7 load balancer or other device that passes the client's IP address in an HTTP header, you will need to enable this module. For use in situations where multiple clients appear to come from one IP address.
--with-http_addition_module
This module works as an output filter, enabling you to add content of a different location before or after that of the location itself.
--with-http_xslt_module
This module will handle transformations of XML responses, based on one or more XSLT stylesheets. (Requires the libxml2 and libxslt libraries.)
--with-http_image_filter_module
This module is able to act as a filter on images, processing them before handing them over to the client. (Requires the libgd library.)
--with-http_geoip_module
With this module, you are able to set various variables to use in configuration blocks to make decisions based on the geographic location found for a client's IP address. (Requires the MaxMind GeoIP library and the corresponding precompiled database files.)
--with-http_sub_module
This module implements a substitution filter, replacing one string in the response with another. (A word of caution: using this module implicitly disables the caching of headers.)
--with-http_dav_module
Enabling this module will activate the configuration directives for using WebDAV. Note that this module should only be enabled on a need-to-use basis, as it could present security problems if configured incorrectly.
--with-http_flv_module
If you need to be able to stream Flash video files, this module will provide pseudo-streaming.
--with-http_mp4_module
This module supports pseudo-streaming for H.264/AAC files.
--with-http_gzip_static_module
Use this module if you would like to support sending pre-compressed versions of static files when the resource is called without the .gz ending.
--with-http_gunzip_module
This module will decompress pre-compressed content for clients that do not support gzip encoding.
--with-http_random_index_module
If you would like to serve an index file chosen at random from the files in a directory, then this module needs to be enabled.
--with-http_secure_link_module
This module provides a mechanism to hash a link to a URL, so that only those with the proper password would be able to calculate the link.
--with-http_stub_status_module
Enabling this module will help you gather statistics from NGINX itself. The output can be graphed using RRDtool or something similar.
As you can see, these are all modules that build upon the http module, providing extra functionality. Enabling the modules at compile time should not affect runtime performance at all. Using the modules later in the configuration is where performance may be impacted.
I would therefore recommend the following configure options for a web accelerator/proxy:
And the following for a web server:
The difference lies in where NGINX will be faced with clients. The web acceleration role takes care of terminating SSL requests as well as dealing with proxied clients and making decisions based on where a client came from. The web server role only needs to provide default file serving capability.
I would recommend always enabling the stub_status module, as it provides a means of gathering metrics on how your NGINX is performing.
There are also a number of http modules that are normally activated, but may be disabled by setting the appropriate configuration option --without-<module-name>_module. If you have no use for these modules in your configuration, you can safely disable them.
Option
Explanation
--without-http_charset_module
The charset module is responsible for setting the Content-Type response header, as well as converting from one charset to another.
--without-http_gzip_module
The gzip module works as an output filter, compressing content as it's delivered to the client.
--without-http_ssi_module
This module is a filter that processes Server Side Includes. If the Perl module is enabled, an additional SSI command (perl) is available.
--without-http_userid_module
The userid module enables NGINX to set cookies that can be used for client identification. The variables $uid_set and $uid_got can then be logged for user tracking.
--without-http_access_module
The access module controls access to a location based on IP address.
--without-http_auth_basic_module
This module limits access via HTTP Basic Authentication.
--without-http_autoindex_module
The autoindex module enables NGINX to generate a directory listing for directories that have no index file.
--without-http_geo_module
This module enables you to set up configuration variables based on a client's IP address and then take action on the value of those variables.
--without-http_map_module
The map module enables you to map one variable to another.
--without-http_split_clients_module
This module creates variables that can be used for A/B testing.
--without-http_referer_module
This module enables NGINX to block requests based on the Referer HTTP header.
--without-http_rewrite_module
The rewrite module allows you to change URIs based on various conditions.
--without-http_proxy_module
The proxy module allows NGINX to pass requests onto another server or group of servers.
--without-http_fastcgi_module
The FastCGI module enables NGINX to pass requests to a FastCGI server.
--without-http_uwsgi_module
This module enables NGINX to pass requests to a uWSGI server.
--without-http_scgi_module
The SCGI module enables NGINX to pass requests to an SCGI server.
--without-http_memcached_module
This module enables NGINX to interact with a memcached server, placing responses to queries into a variable.
--without-http_limit_conn_module
This module enables NGINX to set connection limits based on certain keys, usually an IP address.
--without-http_limit_req_module
With this module, NGINX can limit the request rate per key.
--without-http_empty_gif_module
The empty GIF module produces a 1 x 1-pixel in-memory transparent GIF.
--without-http_browser_module
The browser module allows for configurations based on the User-Agent HTTP request header. Variables are set based on the version found in this header.
--without-http_upstream_ip_hash_module
This module defines a set of servers that may be used in conjunction with the various proxy modules.
As with many open source projects, there is an active developer community surrounding NGINX. Thanks to NGINX's modular nature, this community is able to develop and publish modules to provide additional functionality. They cover a wide range of applications, so it pays to take a look at what is available before embarking on developing your own module.
The procedure for installing a third-party module is fairly straightforward:
This procedure will give you an nginx binary with the additional functionality of that module.
Keep in mind that many third-party modules are of an experimental nature. Test using a module first before rolling it out on production systems and remember that the mainline releases of NGINX may have API changes that can cause problems with third-party modules.
Special mention should be made here of the ngx_lua third-party module. The ngx_lua module serves to enable Lua instead of Perl as a configuration time embedded scripting language. The great advantage this module has over the perl module is its non-blocking nature and tight integration with other third-party modules. The installation instructions are fully described at https://github.com/openresty/lua-nginx-module#installation. We will be using this module as an example of installing a third-party module in the next section.
Now that you have gotten a glimpse at what all the various configuration options are for, you can design a binary that precisely fits your needs. The following example specifies the prefix, user, group, paths, disables some modules, enables some others, and includes a couple of third-party modules:
Following a lot of output showing what configure was able to find on your system, a summary is printed out as follows:
As you can see, configure found all the items we were looking for, and acknowledged our preferences for certain paths. Now you can build your nginx and install it, as mentioned at the beginning of the chapter.
This chapter has introduced you to the various modules available for NGINX. By compiling your own binary, you are able to tailor what functionality your nginx will provide. Building and installing software will not be new to you, so not a lot of time was spent on creating a build environment or making sure that all dependencies were present. An NGINX installation should be one that fits your needs, so feel free to enable or disable modules as you see fit.
Next up, we will present an overview of basic NGINX configuration, to get a feel for how to configure NGINX in general.
The NGINX configuration file follows a very logical format. Learning this format and how to use each section is one of the building blocks that will help you create a configuration file by hand. Constructing a configuration involves specifying global parameters as well as directives for each individual section. These directives and how they fit into the overall configuration file is the main subject of this chapter. The goal is to understand how to create the right configuration file to meet your needs.
This chapter will help you reach this goal by explaining the following topics:
The basic NGINX configuration file is set up in a number of sections. Each section is delineated as shown:
It is important to note that each directive line ends with a semicolon (;). This marks the end of line. The curly braces ({}) actually denote a new configuration context, but we will read these as sections for the most part.
The global section is used to configure the parameters that affect the entire server and is an exception to the format shown in the preceding section. The global section may include configuration directives, such as user and worker_processes, as well as sections, such as events. There are no open and closing braces ({}) surrounding the global section.
The most important configuration directives in the global context are shown in the following table. These configuration directives will be the ones that you will be dealing with for the most part.
Global configuration directives
Explanation
user
The user and group under which the worker processes run is configured using this parameter. If the group is omitted, a group name equal to that of the user is used.
worker_processes
This directive shows the number of worker processes that will be started. These processes will handle all the connections made by the clients. Choosing the right number depends on the server environment, the disk subsystem, and the network infrastructure. A good rule of thumb is to set this equal to the number of processor cores for CPU-bound loads and to multiply this number by 1.5 to 2 for the I/O bound loads.
error_log
This directive is where all the errors are written. If no other error_log is given in a separate context, this log file will be used for all errors, globally. A second parameter to this directive indicates the level at which (debug, info, notice, warn, error, crit, alert, and emerg) errors are written in the log. Note that the debug-level errors are only available if the --with-debug configuration switch is given at compilation time.
pid
This directive is the file where the process ID of the main process is written, overwriting the compiled-in default.
use
This directive indicates the connection processing method that should be used. This will overwrite the compiled-in default and must be contained in an events context, if used. It will not normally need to be overridden, except when the compiled-in default is found to produce errors over time.
worker_connections
This directive configures the maximum number of simultaneous connections that a worker process may have opened. This includes, but is not limited to, client connections and connections to upstream servers. This is especially important on reverse proxy servers—some additional tuning may be required at the operating system level in order to reach this number of simultaneous connections.
Here is a small example using each of these directives:
This section will be placed at the top of the nginx.conf configuration file.
The include files can be used anywhere in your configuration file to help it be more readable and to enable you to reuse parts of your configuration. To use them, make sure that the files themselves contain the syntactically correct NGINX configuration directives and blocks; then specify a path to those files:
A wildcard may appear in the path to match multiple files:
If the full path is not given, NGINX will search relative to its main configuration file.
A configuration file can easily be tested by calling NGINX as follows:
