www.it-ebooks.info
Mastering NGINX
An in-depth guide to configuring NGINX for any
situation, including numerous examples and
reference tables describing each directive
Dimitri Aivaliotis
BIRMINGHAM - MUMBAI
www.it-ebooks.info
Mastering NGINX
Copyright © 2013 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
Production Reference: 1070313
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK..
ISBN 978-1-84951-744-7
www.packtpub.com
Cover Image by Asher Wishkerman ()
www.it-ebooks.info
Credits
Author
Project Coordinator
Dimitri Aivaliotis
Abhishek Kori
Reviewers
Proofreader
Yasir Adnan
Aaron Nash
Andrew Alexeev
Antonio P. P. Almeida
Rainer Duffner
Indexer
Tejal Soni
Graphics
Acquisition Editor
Aditi Gajjar
Usha Iyer
Lead Technical Editor
Azharuddin Sheikh
Production Coordinator
Manu Joseph
Cover Work
Technical Editors
Varun Pius Rodrigues
Manu Joseph
Lubna Shaikh
www.it-ebooks.info
About the Author
Dimitri Aivaliotis works as a Systems Architect at a hosting provider in Zurich,
Switzerland. His career has taken him from building a Linux-based computer network
for a school up through dual-datacenter high-availability infrastructures for banks
and online portals. He has spent over a decade solving his customers’ problems and
discovered NGINX along the way. He uses the software daily to provide web serving,
proxying, and media-streaming services to his customers.
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.
This is his first book.
I would like to thank John Blackwell and Phil Margolis for reading
early drafts of the manuscript. Their criticism and tips have helped
me greatly and made this a better book. I would also like to thank the
technical reviewers for providing constructive feedback and pointing
out errors I have made along the way. Any remaining errors are of
course my own.
The team at Packt Publishing has been really supportive in
getting this project off the ground. Their faith in me as a writer
has bolstered me during the dark times of missed deadlines.
The knowledge and support of the NGINX, Inc. team has been
instrumental in filling in the gaps in my understanding of how
NGINX works. I could not have written this book without them.
An especially heartfelt thanks goes out to my family. My wife
and children have had to cope with my many writing sessions.
Their patience during this time is greatly appreciated.
www.it-ebooks.info
About the Reviewers
Yasir Adnan lives in Dhaka, Bangladesh. He is a computer science student.
He also works as a freelance programmer. He has worked on both mobile and
web applications. Nowadays he mainly develops mobile applications. He can
be reached at
Andrew Alexeev is a co-founder of NGINX, Inc.—the high performance
web company behind the NGINX web server. Prior to joining NGINX, Inc. at
the beginning of 2011, Andrew worked in the Internet industry and in a variety
of ICT divisions for enterprises. Andrew holds a diploma in Electronics from
St. Petersburg Electrotechnical University and an executive MBA from Antwerp
Management School.
Antonio P.P. Almeida (@perusio) has been obsessed with NGINX and
high-performance web stacks ever since he was trying to develop for Drupal
on a battered 1.3 GHz Centrino-based laptop and Apache’s resource appetite
made NGINX inevitable. He has been learning how to get the most out of
NGINX in all possible kinds of applications, in particular all the subtleties of
NGINX configuration language. He lives and works in Paris. Besides NGINX,
his other main obsessions are obscure late Italian medieval music, cinema,
and how to make Drupal more awesome.
www.it-ebooks.info
Rainer Duffner received a degree in Information Systems from the University of
Applied Science in Konstanz, Germany, and currently works as a Systems Engineer
at EveryWare AG, where he helps customers get the most out of their managed
dedicated FreeBSD, Linux, and Solaris servers. He lives in a small town next to
Zurich, Switzerland, and enjoys spending his free time on a mountain bike around
Zurich and the Swiss mountains.
I’d like to thank Dimitri for the opportunity to help review this fine
book. It’s a useful resource all along.
www.it-ebooks.info
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related
to your book.
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 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.
TM
Do you need instant solutions to your IT questions? PacktLib is Packt’s online
digital book library. Here, you can access, read and search across Packt’s entire
library of books.
Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials
for immediate access.
www.it-ebooks.info
www.it-ebooks.info
Dedicated to my father, who has always said I can do anything
I set my mind to.
www.it-ebooks.info
www.it-ebooks.info
Table of Contents
Preface1
Chapter 1: Installing NGINX and Third-Party Modules
7
Installing NGINX using a package manager
8
CentOS8
Debian
9
Installing NGINX from source
9
Preparing a build environment
10
Compiling from source
10
Table: Common configure options
Table: Configure options for optimization
Configuring for web or mail service
Configure options for a mail proxy
Table: Mail configure options
Configure the options to specify paths
Table: HTTP configure options
11
12
12
12
12
13
13
Enabling various modules
14
Disabling unused modules
16
Table: HTTP module configure options
Table: Disable configure options
Finding and installing third-party modules
Putting it all together
Summary
Chapter 2: A Configuration Guide
The basic configuration format
NGINX global configuration parameters
Table: Global configuration directives
Using include files
www.it-ebooks.info
14
16
18
19
20
21
21
22
22
24
Table of Contents
The HTTP server section
Client directives
24
25
Table: HTTP client directives
25
File I/O directives
26
Hash directives
27
Socket directives
28
Table: HTTP file I/O directives
26
Table: HTTP hash directives
27
Table: HTTP socket directives
28
Sample configuration
The virtual server section
29
30
Locations – where, when, and how
34
The mail server section
36
Full sample configuration
Summary
38
40
Table: listen parameters
Table: Location modifiers
Table: Location-only directives
Table: Mail module directives
Table: Mail SSL directives
30
34
35
37
37
Chapter 3: Using the Mail Module
41
Chapter 4: NGINX as a Reverse Proxy
65
Basic proxy service
41
POP3 service
43
IMAP service
44
SMTP service
45
Using SSL/TLS
46
Complete mail example
48
Authentication service
50
Combining with memcached
58
Interpreting log files
60
Operating system limits
63
Summary64
Introduction to reverse proxying
The proxy module
Table: Proxy module directives
Legacy servers with cookies
66
67
67
72
The upstream module
73
Table: Upstream module directives
Keepalive connections
Load-balancing algorithms
73
74
75
[ ii ]
www.it-ebooks.info
Table of Contents
Types of upstream servers
Single upstream server
Multiple upstream servers
Non-HTTP upstream servers
76
76
77
79
Memcached upstream servers
FastCGI upstream servers
SCGI upstream servers
uWSGI upstream servers
79
80
80
81
Converting an "if"-fy configuration to a more modern interpretation
81
Using error documents to handle upstream problems
85
Determining the client's real IP address
87
Summary88
Chapter 5: Reverse Proxy Advanced Topics
Security through separation
Encrypting traffic with SSL
Authenticating clients using SSL
Blocking traffic based on originating IP address
Isolating application components for scalability
Reverse proxy performance tuning
Buffering
Table: Proxy module buffering directives
89
90
90
92
95
97
101
101
101
Caching
104
Compressing
111
Table: Proxy module caching directives
Storing
105
109
Table: Gzip module directives
112
Summary114
Chapter 6: The NGINX HTTP Server
NGINX's architecture
The HTTP core module
The server
Table: HTTP server directives
115
115
117
117
118
Logging
119
Finding files
122
Name resolution
124
Client interaction
126
Table: HTTP logging directives
Table: Log format variables
120
121
Table: HTTP file-path directives
124
Table: Name resolution directives
125
Table: HTTP client interaction directives
126
[ iii ]
www.it-ebooks.info
Table of Contents
Using limits to prevent abuse
128
Restricting access
133
Streaming media files
137
Predefined variables
138
Using NGINX with PHP-FPM
141
Table: HTTP limits directives
129
Table: HTTP access module directives
133
Table: HTTP streaming directives
137
Table: HTTP variables
139
Table: FastCGI directives
141
An example Drupal configuration
146
Wiring NGINX and uWSGI together
154
An example Django configuration
154
Summary157
Chapter 7: NGINX for the Developer
Caching integration
No application caching
Caching in the database
Table: Memcached module directives
159
159
160
162
164
Caching in the filesystem
165
Changing content on-the-fly
The addition module
168
169
Table: Header modifying directives
165
Table: HTTP addition module directives
169
The sub module
170
The xslt module
171
Table: HTTP sub module directives
171
Table: HTTP XSLT module directives
172
Using Server Side Includes
172
Decision-making in NGINX
176
Creating a secure link
Generating images
179
181
Tracking website visitors
185
Table: Server Side Includes directives
Table: Server Side Includes commands
172
173
Table: Perl module directives
176
Table: Image filter directives
181
Table: UserID module directives
186
Preventing inadvertent code execution
187
Summary188
[ iv ]
www.it-ebooks.info
Table of Contents
Chapter 8: Troubleshooting Techniques
Analyzing log files
Error log file formats
Error log file entry examples
Configuring advanced logging
Debug logging
Switching binaries at runtime
Using access logs for debugging
Common configuration errors
Using if instead of try_files
Using if as a hostname switch
Not using the server context to best effect
Operating system limits
File descriptor limits
Network limits
Performance problems
Using the Stub Status module
Summary
189
189
190
191
194
194
194
201
203
204
205
206
207
208
210
211
213
214
Appendix A: Directive Reference
215
Appendix B: Rewrite Rule Guide
265
Table: Directive reference
215
Introducing the rewrite module
265
Table: Rewrite module directives
Creating new rewrite rules
Translating from Apache
Rule #1: Replace directory and file existence checks with try_files
Rule #2: Replace matches against REQUEST_URI with a location
Rule #3: Replace matches against HTTP_HOST with a server
Rule #4: Replace RewriteCond with if for variable checks
Summary
269
270
272
272
273
274
276
277
Appendix C: The NGINX Community
279
Appendix D: Persisting Solaris Network Tunings
Index
283
287
Mailing list
IRC channel
Web resources
Writing a good bug report
Summary
[v]
www.it-ebooks.info
279
280
280
280
281
www.it-ebooks.info
Preface
NGINX is a high-performance web server designed to use very few system
resources. There are many how-to's and example configurations floating around on
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.
www.it-ebooks.info
Preface
What this book covers
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 are 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 web serving problems.
Chapter 7, NGINX for the Developer, shows how NGINX can be integrated with
your application to deliver content to your users more quickly.
Chapter 8, 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, 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, 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.
[2]
www.it-ebooks.info
Preface
What you need for this book
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:
• A build environment: Compiler, header files, and a few more
• NGINX: Most recent version should be fine
• Ruby: Best installed from
• Perl: Default version should be fine
Who this book is for
This book is for experienced systems administrators or systems engineers, familiar
with installing and configuring servers to meet specific needs. You do not need
to have experience using NGINX already.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: "NGINX will attempt to build a dependent
library statically if you include a ––with-<library>=
option to configure."
A block of code is set as follows:
$
$
$
$
$
export
export
export
export
export
BUILD_DIR=`pwd`
NGINX_INSTALLDIR=/opt/nginx
VAR_DIR=/home/www/tmp
LUAJIT_LIB=/opt/luajit/lib
LUAJIT_INC=/opt/luajit/include/luajit-2.0
When we wish to draw your attention to a particular part of a code block, the relevant
lines or items are set in bold:
$
$
$
$
$
export
export
export
export
export
BUILD_DIR=`pwd`
NGINX_INSTALLDIR=/opt/nginx
VAR_DIR=/home/www/tmp
LUAJIT_LIB=/opt/luajit/lib
LUAJIT_INC=/opt/luajit/include/luajit-2.0
[3]
www.it-ebooks.info
Preface
Any command-line input or output is written as follows:
$ mkdir $HOME/build
$ cd $HOME/build && tar xzf nginx-<version-number>.tar.gz
New terms and important words are shown in bold. Words that you see on the screen,
in menus or dialog boxes for example, 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.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to ,
and mention the book title via 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 on www.packtpub.com/authors.
Customer support
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.
Downloading the example code
You can download the example code files for all Packt books you have purchased
from your account at . If you purchased this book
elsewhere, you can visit and register to
have the files e-mailed directly to you.
[4]
www.it-ebooks.info
Preface
Errata
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 would 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 ktpub.
com/support, 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 on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from />
Piracy
Piracy of copyright 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 with a link to the suspected
pirated material.
We appreciate your help in protecting our authors, and our ability to bring
you valuable content.
Questions
You can contact us at if you are having a problem
with any aspect of the book, and we will do our best to address it.
[5]
www.it-ebooks.info
www.it-ebooks.info
Installing NGINX and
Third-Party Modules
NGINX was first conceived to be an HTTP server. It was created to solve the C10K
problem, described by Daniel Kegel at of
designing a web server to handle 10,000 simultaneous connections. NGINX is able
to 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 itself and how to get the correct modules installed and
configured. NGINX is modular by design, and there is a rich community of thirdparty 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:
• Installing NGINX using a package manager
• Installing NGINX from source
• Configuring for web or mail service
• Enabling various modules
• Finding and installing third-party modules
• Putting it all together
www.it-ebooks.info
Installing NGINX and Third-Party Modules
Installing NGINX using a package
manager
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:
• Linux (deb-based)
sudo apt-get install nginx
• Linux (rpm-based)
sudo yum install nginx
• FreeBSD
sudo pkg_install -r nginx
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 RBAC
(Role-based access control), 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
Users of distributions without an nginx
package (such as CentOS), can use the following instructions to install pre-tested,
pre-compiled binaries.
CentOS
Add the NGINX repository to your yum configuration by creating the following file:
sudo vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl= />gpgcheck=0
enabled=1
[8]
www.it-ebooks.info