41,99 €
A practical book on real-world NGINX deployments to get you up and running quickly.
About This Book
Who This Book Is For
This book is aimed at smaller-to-medium developers, who are just getting started with NGINX. It assumes they already understand the basics of how a web server works and how basic networking works.
What You Will Learn
In Detail
NGINX Cookbook covers the basics of configuring NGINX as a web server for use with common web frameworks such as WordPress and Ruby on Rails, through to utilization as a reverse proxy. Designed as a go-to reference guide, this book will give you practical answers based on real-world deployments to get you up and running quickly.
Recipes have also been provided for multiple SSL configurations, different logging scenarios, practical rewrites, and multiple load balancing scenarios. Advanced topics include covering bandwidth management, Docker container usage, performance tuning, OpenResty, and the NGINX Plus commercial features.
By the time you've read this book, you will be able to adapt and use a wide variety of NGINX implementations to solve any problems you have.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 248
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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: August 2017
Production reference: 1300817
ISBN 978-1-78646-617-4
www.packtpub.com
Author
Tim Butler
Copy Editor
Tom Jacob
Reviewers
Claudio Borges
Jesse Lawson
Project Coordinator
Judie Jose
Commissioning Editor
Pratik Shah
Proofreader
Safis Editing
Acquisition Editors
Prachi Bisht
Subho Gupta
Indexer
Tejal Daruwale Soni
Content Development Editor
Monika Sangwan
Graphics
Kirk D'Penha
Technical Editor
Bhagyashree Rai
Production Coordinator
Arvindkumar Gupta
Tim Butler is currently working in the web hosting industry and has nearly 20 years of experience. He currently maintains hyper-converged storage/compute platforms and is an architect of high throughput web logging and monitoring solutions.
You can follow him on Twitter using his Twitter handle, @timbutler, where he (infrequently) posts about hosting, virtualization, NGINX, containers, and a few other hobbies.
Claudio Borges is a systems engineer with a computer science degree and over 15 years of experience in Linux/BSD. He has strong knowledge of systems administration and deployment with extensive experience in developing tools to automate systems and tasks.
Jesse Lawson is a PhD student at Northcentral University and an information systems administrator at Butte College in Oroville, CA. His research addresses two primary areas: consumer psychology in higher education administration, and data science and analytics in the social sciences. His dissertation explores how machine learning models compare to human-generated processes of predicting college student outcomes, and what it means if people are better at predicting student dropout behavior than algorithms. He is the author of the bestselling book Data Science in Higher Education, published by CreateSpace Independent Publishing Platform; he is a technical reviewer for Packt Publishing; and a former technical reviewer for the International Journal of Computer Science and Innovation.
For support files and downloads related to your book, please visit www.PacktPub.com. 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://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Let's Get Started
Introduction
A quick installation guide
How to do it...
Packages – RHEL/CentOS
Packages – Debian/Ubuntu
Compiling from scratch
Debian/Ubuntu
CentOS/RHEL
Testing
How to do it...
There's more...
Configuring NGINX
How to do it...
How it works...
Enabling modules
How to do it...
See also
Deploying a basic site
How to do it...
How it works...
Basic monitoring
How to do it...
How it works...
Real-time statistics
How to do it...
How it works...
See also
Common PHP Scenarios
Introduction
Configuring NGINX for WordPress
Getting ready
How to do it...
How it works...
There's more...
WordPress multisite with NGINX
How to do it...
Subdomains
See also
Running Drupal using NGINX
Getting ready
How to do it...
How it works...
See also
Using NGINX with MediaWiki
Getting ready
How to do it...
See also
Using Magento with NGINX
Getting ready
How to do it...
How it works...
See also
Configuring NGINX for Joomla
Getting ready
How to do it...
See also
Common Frameworks
Introduction
Setting up Django with NGINX
Getting ready
How to do it...
How it works....
See also
Setting up NGINX with Express
Getting ready
How to do it...
How it works....
See also
Running Ruby on Rails with NGINX
Getting ready
How to do it...
How it works...
See also
Easy Flask with NGINX
Getting ready
How to do it...
How it works...
Laravel via NGINX
Getting ready
How to do it...
How it works...
See also
Meteor applications with NGINX
Getting ready
How to do it...
How it works...
High speed Beego with NGINX
Getting ready
How to do it...
All About SSLs
Introduction
Basic SSL certificates
Getting ready
How to do it...
How it works...
Enabling HTTP/2 on NGINX
How to do it...
See also
Configuring HSTS in NGINX
How to do it...
There's more...
Easy SSL certificates with Let's Encrypt
How to do it...
See also
Making NGINX PCI DSS compliant
How to do it...
How it works...
See also
OCSP stapling with NGINX
How to do it...
See also
Achieving full A+ Qualys rating
How to do it...
How it works...
See also
Logging
Introduction
Logging to syslog
How to do it...
Remote syslog
See also
Customizing web access logs
How to do it...
See also
Virtual host log format
How to do it...
Application focused logging
How to do it...
Logging TLS mode and cipher information
How to do it...
Logging POST data
How to do it...
Conditional logging
How to do it...
Using the Elastic Stack
How to do it...
Elasticsearch
Logstash
Kibana
See also
Rewrites
Introduction
Redirecting non-www to www-based sites
How to do it...
How it works...
See also
Redirecting to a new domain
How to do it...
How it works...
There's more...
Blocking malicious user agents
How to do it...
How it works...
There's more...
Redirecting all calls to HTTPS to secure your site
How to do it...
There's more...
See also
Redirecting pages and directories
How to do it...
Single page redirect
Full directory redirect
How it works...
See also
Redirecting 404 errors through a search page
How to do it...
How it works...
Reverse Proxy
Introduction
Configuring NGINX as a simple reverse proxy
Getting ready
How to do it...
How it works...
There's more...
See also
Content caching with NGINX
Getting ready
How to do it...
How it works...
There's more...
See also
Monitoring cache status
Getting ready
How to do it...
How it works...
See also
Microcaching
Getting ready
How to do it...
How it works...
Serving from cache when your backend is down
Getting ready
How to do it...
How it works...
There's more...
See also
SSL termination proxy
Getting ready
How to do it...
See also
Rate limiting
How to do it...
How it works...
There's more...
See also
Load Balancing
Introduction
Basic balancing techniques
Round robin load balancing
Getting ready
How to do it...
How it works...
There's more...
See also
Least connected load balancing
Getting ready
How to do it...
How it works...
Hash-based load balancing
How to do it...
How it works...
There's more...
See also
Testing and debugging NGINX load balancing
Getting ready
How to do it...
There's more...
See also
TCP / application load balancing
How to do it...
How it works...
Easy testing
There's more...
See also
NGINX as an SMTP load balancer
How to do it...
How it works...
There's more...
See also
Advanced Features
Introduction
Authentication with NGINX
Getting ready
How to do it...
How it works...
There's more...
See also
WebDAV with NGINX
Getting ready
How to do it...
How it works...
See also
Bandwidth management with NGINX
Getting ready
How to do it...
How it works...
There's more...
See also
Connection limiting with NGINX
Getting ready
How to do it...
How it works...
There's more...
See also
Header modification with NGINX
Getting ready
How to do it...
Caching static content
Removing server name and version
Extra debug headers
See also
Docker Containers
Introduction
Installing Docker
NGINX web server via Docker
Getting ready
How to do it...
How it works...
There's more...
See also
NGINX reverse proxy via Docker
Getting ready
How to do it...
How it works...
There's more...
See also
Docker Compose with NGINX
Getting ready
How to do it...
How it works...
See also
NGINX load balancing with Docker
Getting ready
How to do it...
How it works...
See also
Performance Tuning
Introduction
Gzipping content in NGINX
Getting ready
How to do it...
How it works...
There's more...
See also
Enhancing NGINX with keep alive
Getting ready
How to do it...
How it works...
See also
Tuning worker processes and connections
Getting ready
How to do it...
Worker processes
Worker connections
There's more...
See also
Fine tuning basic Linux system limits
Getting ready
How to do it...
See also
Integrating ngx_pagespeed
Getting ready
How to do it...
How it works...
There's more...
See also
OpenResty
Introduction
Installing OpenResty
Getting ready
How to do it...
CentOS
Ubuntu
How it works...
See also
Getting started with OpenResty Lua
Getting ready
How to do it...
How it works...
See also
Lua microservices with OpenResty
Getting ready
How to do it...
How it works...
There's more...
See also
Simple hit counter with a Redis backend
Getting ready
How to do it...
How it works...
See also
Powering API Gateways with OpenResty
Getting ready
How to do it...
How it works...
There's more...
See also
NGINX Plus – The Commercial Offering
Introduction
Installing NGINX Plus
Getting ready
How to do it...
CentOS
Ubuntu
See also
Real-time server activity monitoring
Getting ready
How to do it...
How it works...
There's more...
See also
Dynamic config reloading
Getting ready
How to do it...
How it works...
There's more...
See also
Session persistence
Getting ready
How to do it...
Cookie-based tracking
Learn-based tracking
Route-based tracking
How it works...
See also
NGINX Cookbook covers the basics of configuring NGINX as a web server for use with common web frameworks such as WordPress and Ruby on Rails, through to utilization as a reverse proxy. Designed as a go-to reference guide, this book will give you practical answers based on real-world deployments to get you up and running quickly.
Recipes have also been provided for multiple SSL configurations, different logging scenarios, practical rewrites, and multiple load balancing scenarios. Advanced topics include covering bandwidth management, Docker container usage, performance tuning, OpenResty, and the NGINX Plus commercial features.
By the time you've read this book, you will be able to adapt and use a wide variety of NGINX implementations to solve any problems you have.
Chapter 1, Let's Get Started, goes through some of the basics of NGINX as a refresher. It's aimed as an entry point so that there's no assumed knowledge when we move onto some of the more complex structures.
Chapter 2, Common PHP Scenarios, covers examples of the more common PHP scenarios and how to implement them with NGINX. The readers will learn how to configure NGINX and how to deploy a basic site.
Chapter 3, Common Frameworks, covers non-PHP-based frameworks. It will help the readers to understand and implement all of the common non-PHP-based platforms via NGINX.
Chapter 4, All About SSLs, covers installing the various SSL certificates via NGINX and also covers the configuration required to tweak it for certain scenarios.
Chapter 5, Logging, explains that monitoring for errors and access patterns are fundamental to running a server.
Chapter 6, Rewrites, covers how rewrites work and also specific implementations of many of the common scenarios. It will be full of specific, practical examples based on real-world scenarios.
Chapter 7, Reverse Proxy, covers a basic proxy with specific examples of caching and content expiry. This chapter will explain how to configure NGINX as a reverse proxy, content caching, monitoring cache status, microcaching, and many more important scenarios.
Chapter 8, Load Balancing, talks about the load balancing components of NGINX and how to implement them for specific scenarios. In this chapter, you will learn the three important load balancing techniques—round-robin, least connection, and hash-based load balancing.
Chapter 9, Advanced Features, covers some of the lesser used features of NGINX, why they're available, and then how to implement them. This chapter includes authentication, WebDAV, bandwidth management, connection limiting, and header modification with NGINX.
Chapter 10, Docker Containers, runs you through real-world scenarios of using NGINX within a container. It will provide basic Dockerfile configs for common scenarios.
Chapter 11, Performance Tuning, is designed to build upon the existing NGINX configurations and enable specific performance enhancements.
Chapter 12, OpenResty, introduces the concept of OpenResty, a combination of NGINX, Lua scripting, and several additional third-party modules all packaged up ready to use.
Chapter 13, NGINX Plus – The Commercial Offering, shows the readers what features are in the Plus version, as well as how to implement them.
The following is the list of software you require to go through the recipes covered in this book:
NGINX
PHP 7
Ubuntu/CentOS/RHEL
This book is aimed at beginner-to-medium developers who are just getting started with NGINX. It assumes that they already understand the basics of how a web server works and how basic networking works.
In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also). To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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: "To install the latest NGINX release, add the NGINX mainline repository by adding the following to /etc/yum.repos.d/nginx.repo."
A block of code is set as follows:
server { listen 80; server_name server.yourdomain.com; access_log /var/log/nginx/log/host.access.log combined; location / { root /var/www/html; index index.html; }}
Any command-line input or output is written as follows:
mkdir -p /var/www/vhosts
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: "As our configuration is very simple, we can simply accept the default settings and hit Create."
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 email [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:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
You can also download the code files by clicking on the Code Files button on the book's web page at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/NGINX-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 https://www.packtpub.com/sites/default/files/downloads/NGINXCookbook_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.
In this chapter, we will cover the following recipes:
A quick installation guide
Configuring NGINX
Stopping/starting NGINX
Enabling modules
Deploying a basic website
Basic monitoring
Real-time statistics
NGINX is a powerful software suite which has progressed well beyond a basic web server package. Some of the additional features, such as the reverse proxy and load balancing options, are well known.
Originally designed to tackle the C10k problem of handling 10,000 concurrent connections, NGINX differentiated itself from Apache with an event-driven architecture. While Apache 2.4 added event-driven processing also, there are a number of distinct differences where NGINX still remains more flexible.
This book describes how to use NGINX in a number of different scenarios and is aimed at providing you with a working solution rather than being an in-depth review of all NGINX features. If you're unfamiliar with NGINX, I highly recommend that you read Nginx HTTP Server - Third Edition, by Clément Nedelcu, also published by Packt Publishing.
Since the mainline release (currently 1.11.19) has all of the latest features, you'll need to install it directly from the NGINX repositories. Thankfully, NGINX is kind enough to provide Red Hat Enterprise Linux (RHEL), CentOS, SUSE Linux Enterprise Server (SLES), Debian, and Ubuntu repositories, as well as OS X and Windows binaries.
The stable and mainline branches don't necessarily reflect system stability, but configuration and module integration stability. Unless you have third-party integration which requires the stable release, we highly recommend the mainline release.
Different Linux distributions have varying package managers, so we'll briefly cover the installation procedures for the more commonly used ones. If the distribution you use isn't covered here, refer to the official NGINX documentation for further guidance.
To install the latest NGINX release, add the NGINX mainline repository by adding the following to /etc/yum.repos.d/nginx.repo:
[nginx] name=nginx repo baseurl=http://nginx.org/packages/mainline/OS/OSRELEASE/$basearch/ gpgcheck=0 enabled=1
You'll also need to replace OS with either rhel or centos, and replace OSRELEASE with 5, 6, or 7, for your correct release.
Once you have the repository installed, refresh the packages and then install NGINX.
yum update
yum install nginx
If you have any issues, double check your repository for the correct syntax.
First, download the NGINX signing key for the packages and install it:
wget http://nginx.org/keys/nginx_signing.key
apt-key add nginx_signing.key
Then, using your preferred Linux editor, we can add the sources to /etc/apt/sources.list.d/nginx.list:
deb http://nginx.org/packages/mainline/debian/ codename nginxdeb-src http://nginx.org/packages/mainline/debian/ codename nginx
Replace codename with the release name; for example, if you're using Debian 8, this will be set to jessie.
For Ubuntu-based systems, you'll need to use the following:
deb http://nginx.org/packages/mainline/ubuntu/ codename nginxdeb-src http://nginx.org/packages/mainline/ubuntu/ codename nginx
Replace codename with the release name; for example, if you're using Ubuntu 14.04, this will be set to trusty.
After adding the new source, we can then update the apt database and install NGINX:
apt-get update
apt-get install nginx
Installation should now be complete.
Although having the precompiled packages is nice, not all of the modules are available out of the box. NGINX requires you to compile these into the NGINX installation and it's not a simple module like Apache.
You can simply build from source without any of the packaging tools for CentOS or Debian, however, it makes upgrades and compatibility more difficult. By default, user compiled programs will default to /usr/local, which means that any documentation which refers to the package defaults (/usr/etc) will be incorrect.
My preference is to base the build on the official package sources, rather than the plain source code. There aren't many extra steps involved, but it makes the ongoing management much easier. If you're looking for vanilla build instructions (without packages), these are easily available on the web.
On Ubuntu/Debian, install the required build tools:
apt-get install devscripts
This will install quite a few packages on your system, so if you're trying to keep your production environment lean, then I'd recommend that you use a separate build box to complete this.
We can now install the build prerequisites for NGINX:
apt-get build-dep nginx
Once you have the required build dependencies, we can now get a copy of the source code. Again, rather than the plain TAR file, we're going to get the packaged variant so that we can easily build them. Here's how we do it:
mkdir ~/nginxbuild
cd ~/nginxbuild
apt-get source nginx
You should now have a directory with the original TAR file, the Debian description, and any Debian specific patches. The apt-get source command will automatically extract and apply patches, as required, into a source directory.
To build without any changes, enter the directory and create the packages:
cd nginx-1.9.10/
fakeroot debian/rules binary
Compiling the code may take a while, depending on how many processors your workstation or server has. Once it has compiled, you should see two binaries in the parent (nginxbuild) directory. The resulting files should be:
nginx-dbg_1.9.10-1~jessie_amd64.deb
nginx_1.9.10-1~jessie_amd64.deb
You can now install NGINX via the newly compiled package:
sudo dpkg -i nginx_1.9.10-1~jessie_amd64.deb
Like the Debian build process, first we'll need to install the package build tools and the additional Extra Packages For Enterprise Linux (EPEL) repository:
sudo yum install yum-utils epel-release mock
Next, update /etc/yum.repos.d/nginx.repo
