trimstray / nginx-admins-handbook
- пятница, 25 октября 2019 г. в 00:33:54
Shell
How to improve NGINX performance, security, and other important things; @ssllabs A+ 100%, @mozilla A+ 120/100.
My notes on NGINX administration basics, tips & tricks, caveats, and gotchas.
Hi-diddle-diddle, he played on his
fiddle and danced with lady pigs.
Number three said, "Nicks on tricks!
I'll build my house with EN-jin-EKS!".
The Three Little Pigs: Who's Afraid of the Big Bad Wolf?
Before you start playing with NGINX please read an official Beginner’s Guide. It's a great introduction for everyone.
Nginx (/ˌɛndʒɪnˈɛks/ EN-jin-EKS, stylized as NGINX or nginx) is an open source HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server. It is originally written by Igor Sysoev. For a long time, it has been running on many heavily loaded Russian sites including Yandex, Mail.Ru, VK, and Rambler. In the April 2019 NGINX was the most commonly used HTTP server (see Netcraft survey).
NGINX is a fast, light-weight and powerful web server that can also be used as a:
Generally, it provides the core of complete web stacks and is designed to help build scalable web applications. When it comes to performance, NGINX can easily handle a huge amount of traffic. The other main advantage of the NGINX is that allows you to do the same thing in different ways.
NGINX is also known as a Apache Killer. It is event-based, so it does not follow Apache's style of spawning new processes or threads for each web page request. Generally, it was created to solve the C10K problem.
Unlike traditional servers, NGINX doesn't rely on threads to handle requests and it was written with a different architecture in mind - one which is much more suitable for nonlinear scalability in both the number of simultaneous connections and requests per second.
For me, it is a one of the best and most important service that I used in my SysAdmin career.
These essential documents should be the main source of knowledge for you:
In addition, I would like to recommend three great docs focuses on the concept of the HTTP protocol:
If you love security keep your eye on this one: Cryptology ePrint Archive. It provides access to recent research in cryptology and explores many subjects of security (e.g. Ciphers, Algorithms, SSL/TLS protocols). I also recommend to read Bulletproof SSL and TLS. Yep, it's definitely the most comprehensive book about deploying TLS for me.
When I was studying architecture of HTTP servers I became interested in NGINX. I found a lot of information about it but I've never found one guide that covers the most important things in a suitable form. I was a little disappointed.
I was interested in everything: NGINX internals, functions, security best practices, performance optimisations, tips & tricks, hacks and rules, but for me all documents treated the subject lightly.
Of course, Official Documentation is the best place but I know that we also have other great resources:
These are definitely the best assets for us and in the first place you should seek help there.
Moreover, in order to improve your knowledge please see Books chapter. It contains top literature on NGINX.
For me, however, there hasn't been a truly in-depth and reasonably simple cheatsheet which describe a variety of configurations and important cross-cutting topics for HTTP servers. I think, the configuration you provided should work without any talisman. That's why I created this repository.
This handbook is a collection of rules, helpers, notes, papers, best practices, and recommendations gathered and used by me (also in production environments). Many of them refer to external resources.
There are a lot of things you can do to improve NGINX server and this guide will attempt to cover as many of them as possible.
Throughout this handbook you will explore the many features and capabilities of the NGINX. You'll find out, for example, how to testing the performance or how to resolve debugging problems. You will learn configuration guidelines, security design patterns, ways to handle common issues and how to stay out of them. I explained here a few best tips to avoid pitfalls and configuration mistakes.
In this handbook I added set of guidelines and examples has also been produced to help you administer of the NGINX. They give us insight into NGINX internals also.
Mostly, I apply the rules presented here on the NGINX working as a reverse proxy. However, does not to prevent them being implemented for NGINX as a standalone server.
If you do not have the time to read hundreds of articles (just like me) this multipurpose handbook may be useful. I created it in the hope that it will be useful especially for System Administrators and Experts of web-based applications. I think it can also be a good complement to official documentation.
I did my best to make this handbook a single and consistent. Is organized in an order that makes logical sense to me. Of course, I still have a lot to improve and to do. I hope you enjoy it, and fun with it.
Remember about the following most important things:
Do not follow guides just to get 100% of something. Think about what you actually do at your server!
Blindly deploying of the rules described here can damage your web application.
There are no settings that are perfect for everyone.
The only correct approach is to understand your exposure, measure and tune.
These guidelines provides (in some places) recommendations for very restrictive setup.
A real community, however, exists only when its members interact in a meaningful way that deepens their understanding of each other and leads to learning.
If you find something which doesn't make sense, or something doesn't seem right, please make a pull request and please add valid and well-reasoned explanations about your changes or comments.
Before adding a pull request, please see the contributing guidelines.
If this project is useful and important for you, you can bring positive energy by giving some good words or supporting this project. Thank you!
What needs to be done? Look at the following ToDo list:
New chapters:
Existing chapters:
If you have any idea, send it back to me or add a pull request.
This checklist contains all rules (68) from this handbook.
Generally, I think that each of these principles is important and should be considered. I tried, however, to separate them into four levels of priority which I hope will help guide your decision.
Remember, these are only guidelines. My point of view may be different from yours so if you feel these priority levels do not reflect your configurations commitment to security, performance or whatever else, you should adjust them as you see fit.
| RULE | CHAPTER | PRIORITY |
|---|---|---|
| Define the listen directives explicitly with address:port pair Prevents soft mistakes which may be difficult to debug. |
Base Rules | ![]() |
| Prevent processing requests with undefined server names It protects against configuration errors, e.g. traffic forwarding to incorrect backends. |
Base Rules | ![]() |
| Never use a hostname in a listen or upstream directives While this may work, it will comes with a large number of issues. |
Base Rules | ![]() |
| Configure log rotation policy Save yourself trouble with your web server: configure appropriate logging policy. |
Base Rules | ![]() |
| Use HTTP/2 HTTP/2 will make our applications faster, simpler, and more robust. |
Performance | ![]() |
| Enable PCRE JIT to speed up processing of regular expressions NGINX with PCRE JIT is much faster than without it. |
Performance | ![]() |
| Always keep NGINX up-to-date Use newest NGINX package to fix vulnerabilities, bugs, and to use new features. |
Hardening | ![]() |
| Run as an unprivileged user Use the principle of least privilege. This way only master process runs as root. |
Hardening | ![]() |
| Protect sensitive resources Hidden directories and files should never be web accessible. |
Hardening | ![]() |
| Hide upstream proxy headers Don't expose what version of software is running on the server. |
Hardening | ![]() |
| Force all connections over TLS Protects your website especially for handle sensitive communications. |
Hardening | ![]() |
| Use min. 2048-bit private keys 2048 bits private keys are sufficient for commercial use. |
Hardening | ![]() |
| Keep only TLS 1.3 and TLS 1.2 Use TLS with modern cryptographic algorithms and without protocol weaknesses. |
Hardening | ![]() |
| Use only strong ciphers Use only strong and not vulnerable cipher suites. |
Hardening | ![]() |
| Use more secure ECDH Curve Use ECDH Curves with according to NIST recommendations. |
Hardening | ![]() |
| Use strong Key Exchange with Perfect Forward Secrecy Establishes a shared secret between two parties that can be used for secret communication. |
Hardening | ![]() |
| Defend against the BEAST attack The server ciphers should be preferred over the client ciphers. |
Hardening | ![]() |
| HTTP Strict Transport Security Tells browsers that it should only be accessed using HTTPS, instead of using HTTP. |
Hardening | ![]() |
| Reduce XSS risks (Content-Security-Policy) CSP is best used as defence-in-depth. It reduces the harm that a malicious injection can cause. |
Hardening | ![]() |
| Control the behaviour of the Referer header (Referrer-Policy) The default behaviour of referrer leaking puts websites at risk of privacy and security breaches. |
Hardening | ![]() |
| Provide clickjacking protection (X-Frame-Options) Defends against clickjacking attack. |
Hardening | ![]() |
| Prevent some categories of XSS attacks (X-XSS-Protection) Prevents to render pages if a potential XSS reflection attack is detected. |
Hardening | ![]() |
| Prevent Sniff Mimetype middleware (X-Content-Type-Options) Tells browsers not to sniff MIME types. |
Hardening | ![]() |
| Reject unsafe HTTP methods Only allow the HTTP methods for which you, in fact, provide services. |
Hardening | ![]() |
| Prevent caching of sensitive data It helps to prevent critical data (e.g. credit card details, or username) leaked. |
Hardening | ![]() |
| Use pass directive compatible with backend protocol Set pass directive only to working with compatible backend layer protocol. |
Reverse Proxy | ![]() |
| Set properly values of the X-Forwarded-For header Identify clients communicating with servers located behind the proxy. |
Reverse Proxy | ![]() |
| Don't use X-Forwarded-Proto with $scheme behind reverse proxy Prevent pass incorrect value of this header. |
Reverse Proxy | ![]() |
| Organising Nginx configuration Well organised code is easier to understand and maintain. |
Base Rules | ![]() |
| Format, prettify and indent your Nginx code Formatted code is easier to maintain, debug, and can be read and understood in a short amount of time. |
Base Rules | ![]() |
| Use reload option to change configurations on the fly Graceful reload of the configuration without stopping the server and dropping any packets. |
Base Rules | ![]() |
| Use return directive for URL redirection (301, 302) The by far simplest and fastest because there is no regexp that has to be evaluated. |
Base Rules | ![]() |
| Maintaining SSL sessions Improves performance from the clients’ perspective. |
Performance | ![]() |
| Use exact names in a server_name directive where possible Helps speed up searching using exact names. |
Performance | ![]() |
| Avoid checks server_name with if directive It decreases NGINX processing requirements. |
Performance | ![]() |
| Use $request_uri to avoid using regular expressions By default, the regex is costly and will slow down the performance. |
Performance | ![]() |
| Use try_files directive to ensure a file exists Use it if you need to search for a file, it saving duplication of code also. |
Performance | ![]() |
| Use return directive instead of rewrite for redirects Use return directive to more speedy response than rewrite. |
Performance | ![]() |
| Disable unnecessary modules Limits vulnerabilities, improve performance and memory efficiency. |
Hardening | ![]() |
| Hide Nginx version number Don't disclose sensitive information about NGINX. |
Hardening | ![]() |
| Hide Nginx server signature Don't disclose sensitive information about NGINX. |
Hardening | ![]() |
| Use only the latest supported OpenSSL version Stay protected from SSL security threats and don't miss out new features. |
Hardening | ![]() |
| Prevent Replay Attacks on Zero Round-Trip Time 0-RTT is disabled by default but you should know that enabling this option creates a significant security risks. |
Hardening | ![]() |
| Mitigation of CRIME/BREACH attacks Disable HTTP compression or compress only zero sensitive content. |
Hardening | ![]() |
| Deny the use of browser features (Feature-Policy) A mechanism to allow and deny the use of browser features. |
Hardening | ![]() |
| Control Buffer Overflow attacks Prevents errors are characterised by the overwriting of memory fragments of the NGINX process. |
Hardening | ![]() |
| Mitigating Slow HTTP DoS attacks (Closing Slow Connections) Prevents attacks in which the attacker sends HTTP requests in pieces slowly. |
Hardening | ![]() |
| Set and pass Host header only with $host variable Use of the $host is the only one guaranteed to have something sensible. |
Reverse Proxy | ![]() |
| Always pass Host, X-Real-IP, and X-Forwarded headers to the backend It gives you more control of forwarded headers. |
Reverse Proxy | ![]() |
| Enable DNS CAA Policy Allows domain name holders to indicate to CA whether they are authorized to issue digital certificates. |
Others | ![]() |
| Separate listen directives for 80 and 443 Help you maintain and modify your configuration. |
Base Rules | ![]() |
| Use only one SSL config for the listen directive The most of the SSL changes will affect only the default server. |
Base Rules | ![]() |
| Use geo/map modules instead of allow/deny Provides the perfect way to block invalid visitors. |
Base Rules | ![]() |
| Set global root directory for unmatched locations Specifies the root directory for an undefined locations. |
Base Rules | ![]() |
| Don't duplicate index directive, use it only in the http block Watch out for duplicating the same rules. |
Base Rules | ![]() |
| Adjust worker processes You can adjust this value to maximum throughput under high concurrency. |
Performance | ![]() |
| Make an exact location match to speed up the selection process Exact location matches are often used to speed up the selection process. |
Performance | ![]() |
| Use limit_conn to improve limiting the download speed Limits NGINX download speed per connection. |
Performance | ![]() |
| Be careful with trailing slashes in proxy_pass directive Incorrect setting could end up with some strange url. |
Reverse Proxy | ![]() |
| Use custom headers without X- prefix The use of custom headers with X- prefix is discouraged. |
Reverse Proxy | ![]() |
| Tweak passive health checks Improve behaviour of the passive health checks. |
Load Balancing | ![]() |
| Define security policies with security.txt Helps make things easier for companies and security researchers. |
Others | ![]() |
| Map all the things... Map module provides a more elegant solution for clearly parsing a big list of regexes. |
Base Rules | ![]() |
| Use custom log formats This is extremely helpful for debugging specific location directives. |
Debugging | ![]() |
| Use debug mode to track down unexpected behaviour There's probably more detail than you want, but that can sometimes be a lifesaver. |
Debugging | ![]() |
| Disable daemon, master process, and all workers except one This simplifies the debugging and lets test configurations rapidly. |
Debugging | ![]() |
| Use core dumps to figure out why NGINX keep crashing Enable core dumps when your NGINX instance receive an unexpected error or when it crashed. |
Debugging | ![]() |
| Don't disable backends by comments, use down parameter Is a good solution to marks the server as permanently unavailable. |
Load Balancing | ![]() |
Here you'll find a few of the different things I've worked and which included to this repository. I hope that these extras will be useful to you.
Many of these recipes have been applied to the configuration of my private website.
An example configuration is in configuration examples chapter. It's also based on this version of printable high-res hardening cheatsheets.
Read about SSL Labs grading here (SSL Labs Grading 2018).
Short SSL Labs grades explanation:
A+ is clearly the desired grade, both A and B grades are acceptable and result in adequate commercial security. The B grade, in particular, may be applied to configurations designed to support very wide audiences (for old clients).
I finally got A+ grade and following scores:
Look also at the following recommendations. In my opinion, the right configuration of NGINX should give the following SSL Labs scores:
Recommended
Perfect but restrictive
Read about Mozilla Observatory here.
I also got the highest note on the Observatory:
I created two versions of printable posters with hardening cheatsheets (High-Res 5000x8200) based on recipes from this handbook:
For
*.xcfand
A+ with all 100%’s on @ssllabs and 120/100 on @mozilla observatory:
It provides the highest scores of the SSL Labs test. Setup is very restrictive with 4096-bit private key, only TLS 1.2, and also modern strict TLS cipher suites (non 128-bits).
A+ on @ssllabs and 120/100 on @mozilla observatory with TLS 1.3 support:
It provides less restrictive setup with 2048-bit private key, TLS 1.3 and 1.2, and also modern strict TLS cipher suites (128/256-bits). The final grade is also in line with the industry standards. Recommend using this configuration.
I created a set of scripts for unattended installation of NGINX from the raw, uncompiled code. It allows you to easily install, create a setup for dependencies (like zlib or openssl), and customized with installation parameters.
For more information please see Installing from source - Automatic installation chapter.
I created a simple to use generator for static pages with errors to replace the default error pages that comes with any web server like NGINX.
For more information please see HTTP Static Error Pages Generator.
Authors: Valery Kholodkov
Excel in Nginx quickly by learning to use its most essential features in real-life applications.
This short review comes from this book or the store.
Authors: Derek DeJonghe
You’ll find recipes for:
This short review comes from this book or the store.
Authors: Martin Fjordvald, Clement Nedelcu
Harness the power of Nginx to make the most of your infrastructure and serve pages faster than ever.
This short review comes from this book or the store.
Authors: Rahul Sharma
Optimize NGINX for high-performance, scalable web applications.
This short review comes from this book or the store.
Authors: Dimitri Aivaliotis
Written for experienced systems administrators and engineers, this book teaches you from scratch how to configure Nginx for any situation. Step-by-step instructions and real-world code snippets clarify even the most complex areas.
This short review comes from this book or the store.
Authors: Faisal Memon, Owen Garrett, Michael Pleshakov
Learn in this ebook how to get started with ModSecurity, the world’s most widely deployed web application firewall (WAF), now available for NGINX and NGINX Plus.
This short review comes from this book or the store.
Authors: Faisal Memon
This ebook provides step-by-step instructions on replacing Cisco ACE with NGINX and off-the-shelf servers. NGINX helps you cut costs and modernize.
In this ebook you will learn:
This short review comes from this book or the store.
Go to the Table of Contents or read the next chapters:
Something about HTTP.
Something about SSL/TLS.
Explanation of the NGINX mechanisms.
One-liners, commands, utilities for building NGINX, and more
The basic set of rules to keep NGINX in good condition.
A few things for troubleshooting configuration problems.
Many methods to make sure the NGINX as fast as possible.
Hardening approaches and security standards.
A few rules about the NGINX proxy server.
You may improve of some rules about the NGINX working as a load balancer.
Something about other interesting rules.
Here are some configuration examples.