Nginx Essentials - Valery Kholodkov - E-Book

Nginx Essentials E-Book

Valery Kholodkov

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book is ideal for skilled web masters and site reliability engineers who want to switch to Nginx or solidify their knowledge of Nginx. Knowledge of Unix and webmaster skills are required.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 178

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Nginx Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
eBooks, discount offers, and more
Questions
1. Getting Started with Nginx
Installing Nginx
Installing Nginx on Ubuntu
Alternatives
Installing Nginx on Red Hat Enterprise Linux or CentOS/Scientific Linux
Installing Nginx from source files
Downloading the Nginx source files
Troubleshooting
Building Nginx
Troubleshooting
Copying the source code configuration from prebuilt packages
The structure of the Nginx installation
The Nginx configuration folder
The default virtual host folder
The virtual hosts configuration folder
The log folder
The temporary folder
Configuring Nginx
Value types
Variables
Inclusions
Sections
The http section
The server section
The upstream section
The location section
Simple
Exact
Regular expression locations
The if section
The limit_except section
Other section types
Configuration settings' inheritance rules
The First sample configuration
Configuration best practices
Summary
2. Managing Nginx
The Nginx connection processing architecture
Starting and stopping Nginx
Control signals and their usage
Fast shutdown
Graceful shutdown
Reconfiguration
Reopening the log file
Nginx binary upgrade
Graceful worker shutdown
Finalizing the upgrade procedure
Handling difficult cases
Distribution-specific startup scripts
Allocating worker processes
Setting up Nginx to serve static data
Installing SSL certificates
Creating a Certificate Signing Request
Installing an issued SSL certificate
Permanently redirecting from a nonsecure virtual host
Managing temporary files
Communicating issues to developers
Creating a binary with debugging information
Summary
3. Proxying and Caching
Nginx as a reverse proxy
Setting up Nginx as a reverse proxy
Setting the backend the right way
Adding transparency
Handling redirects
Handling cookies
Using SSL
Handling errors
Choosing an outbound IP address
Accelerating downloads
Caching
Configuring caches
Enabling caching
Choosing a cache key
Improving cache efficiency and availability
Handling exceptions and borderline cases
Summary
4. Rewrite Engine and Access Control
The basics of the rewrite engine
More about rewrite rules
Patterns
Captures and positional parameters
Other functionalities of the rewrite engine
Assigning variables
Evaluating predicates using if sections
Replying with a specified HTTP status code
Access control
Restricting access by IP address
Using the geo directive to restrict access by IP address
Using basic authentication for access restriction
Authenticating users with a subrequest
Combining multiple access restriction methods
Summary
5. Managing Inbound and Outbound Traffic
Managing inbound traffic
Limiting the request rate
Limiting the number of simultaneous connections
Limiting the transfer rate of a connection
Applying multiple limitations
Managing outbound traffic
Declaring upstream servers
Using upstream servers
Choosing a request distribution strategy
Configuring backup servers
Determining whether a server is available
Enabling persistent connections
Limiting the transfer rate of an upstream connection
Summary
6. Performance Tuning
Optimizing static file retrieval
Enabling response compression
Optimizing buffer allocation
Enabling SSL session reuse
Worker processes allocation on multi-core systems
Summary
Index

Nginx Essentials

Nginx Essentials

Copyright © 2015 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: July 2015

Production reference: 1170715

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-953-8

www.packtpub.com

Credits

Author

Valery Kholodkov

Reviewers

Markus Jelsma

Jesse Estill Lawson

Daniel Parraz

Commissioning Editor

Dipika Gaonkar

Acquisition Editor

Usha Iyer

Content Development Editor

Nikhil Potdukhe

Technical Editor

Manali Gonsalves

Copy Editor

Roshni Banerjee

Project Coordinator

Vijay Kushlani

Proofreader

Safis Editing

Indexer

Priya Sane

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

Valery Kholodkov is a seasoned IT professional with a decade of experience in creating, building, scaling, and maintaining industrial-grade web services, web applications, and mobile application backends. Throughout his career, he has worked for well-known brands, such as Yandex, Booking.com, and AVG. He currently works for his own consultancy firm. Valery has a deep understanding of technology and is able to express its essence, advantages, and risks to a layman, which makes him an accomplished author of technology books.

About the Reviewers

Markus Jelsma is CTO and co-owner at 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 crawl solutions.

Jesse Estill Lawson is a computer scientist and social science researcher who works in higher education. He has consulted with dozens of colleges across the country to help them design, develop, and deploy computer information systems on everything from Windows and Apache to Nginx and node servers, and he centers his research on the coexistence of data science and sociology. In addition to his technological background, Jesse holds an MA in English and is currently working on his PhD in education. You can learn more about him on his website at http://lawsonry.com.

Daniel Parraz is a Linux systems administrator with 15 years of experience in high-volume e-retailer sites, large system storage, and security enterprises. He is currently working with a managed services provider, where he is responsible for all aspects of Unix-like systems in the organization. Daniel was also a technical editor for Learning Nagios 4, Packt Publishing, and has co-written training material for the IBM DS8000 storage server.

I would like to thank my family, friends, and mentors for their constant support through the years.

www.PacktPub.com

Support files, eBooks, discount offers, and more

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://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.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a 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 9 entirely free books. Simply use your login credentials for immediate access.

Preface

2006 was an exciting year. The disappointment that surrounded the dot-com crash had pretty much been superseded by a renewed and more confident growth of Web 2.0 and inspired a search for technologies of a new age.

At that time, I was looking for a web server to power my projects that would do many things in a different way. After getting some experience in large-scale online projects, I knew that the popular LAMP stack was suboptimal and sometimes did not solve certain challenges, such as efficient uploads, geo-dependent rate limiting, and so on.

After trying and rejecting a number of options, I came to know about Nginx and immediately felt that my search was over. It is small yet powerful, with a clean code base, good extensibility, relevant set of features, and a number of architectural challenges solved. Nginx definitely stood out from the crowd!

I immediately got inspired and felt some affinity to this project. I tried participating in the Nginx community, learned, shared my knowledge, and contributed as much as I could.

With time, my knowledge of Nginx grew. I started to get consultancy requests and have been capable of addressing quite sophisticated cases. After some time, I realized that some of my knowledge might be worth sharing with everyone. That's how I started a blog at www.nginxguts.com.

A blog turned out to be an author-driven medium. A more reader-focused and more thorough medium was in demand, so I set aside some time to assemble my knowledge in the more solid form of a book. That's how the book you're holding in your hands right now came into existence.

What this book covers

Chapter 1, Getting Started with Nginx, gives you the most basic knowledge about Nginx, including how to carry out the very basic installation and get Nginx up and running quickly. A detailed explanation of the structure of the configuration file is given so that you know where exactly code snippets from the rest of the book apply.

Chapter 2, Managing Nginx, explains how to manage an operating Nginx instance(s).

Chapter 3, Proxying and Caching, explains how to turn Nginx into a powerful web proxy and cache.

Chapter 4, Rewrite Engine and Access Control, explains how to use the rewrite engine to manipulate URLs and secure your web resources.

Chapter 5, Managing Inbound and Outbound Traffic, describes how to apply various restrictions to inbound traffic, and how to use and manage upstream.

Chapter 6, Performance Tuning, explains how to squeeze the most out of your Nginx server.

What you need for this book

A good knowledge of Unix-like operating systems is required, presumably Linux, along with some web master experience.

Who this book is for

This book intends to enrich web masters' and site reliability engineers' knowledge of subtleties known to those who have a deep understanding of the Nginx core. At the same time, this book is a from the start guide that allows beginners to easily switch to Nginx under experienced guidance.

Conventions

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, folder names, filenames, file extensions, pathnames, dummy URLs, and user input, are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

types { text/html html htm shtml; text/css css; text/xml xml; image/gif gif; image/jpeg jpeg jpg; application/x-javascript js; application/atom+xml atom; application/rss+xml rss; }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

types { text/html html htm shtml; text/css css; text/xml xml; image/gif gif; image/jpeg jpeg jpg; application/x-javascript js; application/atom+xml atom; application/rss+xml rss; }

Any command-line input or output is written as follows:

# cp /usr/local/nginx/nginx.conf.default /etc/nginx/nginx.conf

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."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Elisions of sections of configuration files are shown as […] or with a comment [… this part of the configuration file is up to you ...]

Reader feedback

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.

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.

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 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

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.

eBooks, discount offers, and more

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.

Questions

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.

Chapter 1. Getting Started with Nginx

Nginx has emerged as a robust and scalable general-purpose web server in the last decade. It is a choice of many webmasters, startup founders, and site reliability engineers because of its simple yet scalable and expandable architecture, easy configuration, and light memory footprint. Nginx offers a lot of useful features, such as on-the-fly compression and caching out of the box.

Nginx integrates with existing web technologies such as Apache web server and PHP, and helps solving day-to-day problems in an easy way. Nginx is backed by a large, active community as well as a consulting company funded by venture capital. Therefore, it is actively supported.

This book will help you get started with Nginx and learn skills necessary to turn it into a powerful tool, a workhorse that will help you to solve your day-to-day challenges.

Installing Nginx

Before you can dive into specific features of Nginx, you need to learn how to install Nginx on your system.

It is strongly recommended that you use prebuilt binary packages of Nginx if they are available in your distribution. This ensures best integration of Nginx with your system and reuse of best practices incorporated into the package by the package maintainer. Prebuilt binary packages of Nginx automatically maintain dependencies for you and package maintainers are usually fast to include security patches, so you don't get any complaints from security officers. In addition to that, the package usually provides a distribution-specific startup script, which doesn't come out of the box.

Refer to your distribution package directory to find out if you have a prebuilt package for Nginx. Prebuilt Nginx packages can also be found under the download link on the official Nginx.org site.

In this chapter, we will quickly go through most common distributions that contain prebuilt packages for Nginx.

Installing Nginx on Ubuntu

The Ubuntu Linux distribution contains a prebuilt package for Nginx. To install it, simply run the following command:

$ sudo apt-get install nginx

The preceding command will install all the required files on your system, including the logrotate script and service autorun scripts. The following table describes the Nginx installation layout that will be created after running this command as well as the purpose of the selected files and folders:

Description

Path/Folder

Nginx configuration files

/etc/nginx

Main configuration file

/etc/nginx/nginx.conf

Virtual hosts configuration files (including default one)

/etc/nginx/sites-enabled

Custom configuration files

/etc/nginx/conf.d

Log files (both access and error log)

/var/log/nginx

Temporary files

/var/lib/nginx

Default virtual host files

/usr/share/nginx/html

Note

Default virtual host files will be placed into /usr/share/nginx/html. Please keep in mind that this directory is only for the default virtual host. For deploying your web application, use folders recommended by Filesystem Hierarchy Standard (FHS).

Now you can start the Nginx service with the following command:

$ sudo service nginx start

This will start Nginx on your system.

Alternatives

The prebuilt Nginx package on Ubuntu has a number of alternatives. Each of them allows you to fine tune the Nginx installation for your system.

Installing Nginx on Red Hat Enterprise Linux or CentOS/Scientific Linux

Nginx is not provided out of the box in Red Hat Enterprise Linux or CentOS/Scientific Linux. Instead, we will use the Extra Packages for Enterprise Linux (EPEL) repository. EPEL is a repository that is maintained by Red Hat Enterprise Linux maintainers, but contains packages that are not a part of the main distribution for various reasons. You can read more about EPEL at https://fedoraproject.org/wiki/EPEL.

To enable EPEL, you need to download and install the repository configuration package:

For RHEL or CentOS/SL 7, use the following link:

http://download.fedoraproject.org/pub/epel/7/x86_64/repoview/epel-release.html

For RHEL/CentOS/SL 6 use the following link:

http://download.fedoraproject.org/pub/epel/6/i386/repoview/epel-release.html

If you have a newer/older RHEL version, please take a look at the How can I use these extra packages? section in the original EPEL wiki at the following link:

https://fedoraproject.org/wiki/EPEL

Now that you are ready to install Nginx, use the following command:

# yum install nginx

The preceding command will install all the required files on your system, including the logrotate script and service autorun scripts. The following table describes the Nginx installation layout that will be created after running this command and the purpose of the selected files and folders:

Description

Path/Folder

Nginx configuration files

/etc/nginx

Main configuration file

/etc/nginx/nginx.conf

Virtual hosts configuration files (including default one)

/etc/nginx/conf.d

Custom configuration files

/etc/nginx/conf.d

Log files (both access and error log)

/var/log/nginx

Temporary files

/var/lib/nginx

Default virtual host files

/usr/share/nginx/html

Note

Default virtual host files will be placed into /usr/share/nginx/html. Please keep in mind that this directory is only for the default virtual host. For deploying your web application, use folders recommended by FHS.

By default, the Nginx service will not autostart on system startup, so let's enable it. Refer to the following table for the commands corresponding to your CentOS version:

Function

Cent OS 6

Cent OS 7

Enable Nginx startup at system startup

chkconfig nginx on

systemctl enable nginx

Manually start Nginx

service nginx start

systemctl start nginx

Manually stop Nginx

service nginx stop

systemctl start nginx

Installing Nginx from source files

Traditionally, Nginx is distributed in the source code. In order to install Nginx from the source code, you need to download and compile the source files on your system.

Note

It is not recommended that you install Nginx from the source code. Do this only if you have a good reason, such as the following scenarios:

You are a software developer and want to debug or extend NginxYou feel confident enough to maintain your own packageA package from your distribution is not good enough for youYou want to fine-tune your Nginx binary

In either case, if you are planning to use this way of installing for real use, be prepared to sort out challenges such as dependency maintenance, distribution, and application of security patches.

In this section, we will be referring to the configuration script. Configuration script is a shell script similar to one generated by autoconf, which is required to properly configure the Nginx source code before it can be compiled. This configuration script has nothing to do with the Nginx configuration file that we will be discussing later.

Downloading the Nginx source files

The primary source for Nginx for an English-speaking audience is Nginx.org. Open http://nginx.org/en/download.html in your browser and choose the most recent stable version of Nginx. Download the chosen archive into a directory of your choice (/usr/local or /usr/src are common directories to use for compiling software):

$ wget -q http://nginx.org/download/nginx-1.7.9.tar.gz

Extract the files from the downloaded archive and change to the directory corresponding to the chosen version of Nginx:

$ tar xf nginx-1.7.9.tar.gz$ cd nginx-1.7.9

To configure the source code, we need to run the ./configure script included in the archive:

$ ./configurechecking for OS + Linux 3.13.0-36-generic i686