Before using the Nginx please read Beginner’s Guide.
Nginx (/ˌɛndʒɪnˈɛks/ EN-jin-EKS) is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server, 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.
To increase your knowledge, read Nginx Documentation.
This is not an official handbook. Many of these rules refer to other resources. It is rather a quick collection of things used by me in production env.
:small_orange_diamond: Nginx Project
:small_orange_diamond: Nginx official read-only mirror
:small_orange_diamond: Nginx boilerplate configs
:small_orange_diamond: Awesome Nginx configuration template
:small_orange_diamond: Nginx static analyzer
:small_orange_diamond: A collection of resources covering Nginx and more
:small_orange_diamond: Nginx Cheatsheet
:small_orange_diamond: Nginx Quick Reference
:small_orange_diamond: Nginx Cheatsheet by Mijdert Stuij
:small_orange_diamond: WAF for Nginx
:small_orange_diamond: ModSecurity for Nginx
:small_orange_diamond: How to Build a Tough NGINX Server in 15 Steps
:small_orange_diamond: Top 25 Nginx Web Server Best Security Practices
:small_orange_diamond: Strong SSL Security on Nginx
:small_orange_diamond: Nginx Tuning For Best Performance by Denji
:small_orange_diamond: Enable cross-origin resource sharing (CORS)
:small_orange_diamond: siege - is an http load testing and benchmarking utility.
:small_orange_diamond: wrk - is a modern HTTP benchmarking tool capable of generating significant load.
:small_orange_diamond: bombardier - fast cross-platform HTTP benchmarking tool written in Go.
:small_orange_diamond: gobench - http/https load testing and benchmarking tool.
:small_orange_diamond: ngxtop
:small_orange_diamond: GoAccess
:small_orange_diamond: Graylog
:small_orange_diamond: Logstash
:small_orange_diamond: Online tool to learn, build, & test Regular Expressions
:small_orange_diamond: Online Regex Tester & Debugger
:small_orange_diamond: SSL Server Test
:small_orange_diamond: Strong ciphers for Apache, Nginx, Lighttpd and more
:small_orange_diamond: Analyse the HTTP response headers by Security Headers
:small_orange_diamond: Analyze your website by Mozilla Observatory
:small_orange_diamond: BBC Digital Media Distribution: How we improved throughput by 4x
:small_orange_diamond: Web cache server performance benchmark: nuster vs nginx vs varnish vs squid
alias ng.test='nginx -t -c /etc/nginx/nginx.conf'
alias ng.reload='systemctl reload nginx'
alias ng.restart='systemctl restart nginx'
alias ng.stop='systemctl stop nginx'
-
Separate listen directives for 80 and 443
...
# For http: server { listen 10.240.20.2:80; ... } # For https: server { listen 10.240.20.2:443 ssl; ... }
-
Organising Nginx configuration
When your configuration grow, the need for organising your code will also grow. Well organised code is:
- Easier to understand.
- Easier to maintain.
- Easier to work with.
Use
include
directive to attach your nginx specific code to global config, contexts and other.# Store this configuration in https-ssl-common.conf cat /etc/nginx/domain.com/commons/https-ssl-common.conf; listen 10.240.20.2:443 ssl; root /etc/nginx/error-pages/other; ssl_certificate /etc/nginx/domain.com/certs/nginx_domain.com_bundle.crt; ssl_certificate_key /etc/nginx/domain.com/certs/domain.com.key; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_protocols TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL; # Uncomment if issued by the CA: # ssl_stapling on; # ssl_stapling_verify on; ssl_ecdh_curve secp384r1; ssl_dhparam /etc/nginx/dhparams_4096.pem; # And include this in server section: server { include /etc/nginx/domain.com/commons/https-ssl-common.conf; server_name domain.com www.domain.com; ...
-
Use default_server directive at the beginning
Nginx should prevent processing requests with undefined server names - also traffic on ip address. It also protects against configuration errors and providing incorrect backends.
server { listen 10.240.20.2:443 ssl; # Place it at the beginning of the configuration file. server_name default_server; location / { # serve static file (error page): root /etc/nginx/error-pages/404; # or redirect: # return 301 https://badssl.com; } } server { listen 10.240.20.2:443 ssl; server_name domain.com; ... } server { listen 10.240.20.2:443 ssl; server_name app.domain.com; ... }
-
Force all connections over TLS
You should always use HTTPS instead of HTTP to protect your website, even if it doesn’t handle sensitive communications.
server { listen 10.240.20.2:80; server_name domain.com; return 301 https://$host$request_uri; } server { listen 10.240.20.2:443 ssl; server_name domain.com; ... }
-
Use geo/map modules instead allow/deny
Creates variables with values depending on the client IP address. Use map or geo modules (one of them) to prevent users abusing your servers.
# Map module: map $remote_addr $globals_internal_map_acl { # Status code: # - 0 = false # - 1 = true default 0; ### INTERNAL ### 10.255.10.0/24 1; 10.255.20.0/24 1; 10.255.30.0/24 1; 192.168.0.0/16 1; } # Geo module: geo $globals_internal_geo_acl { # Status code: # - 0 = false # - 1 = true default 0; ### INTERNAL ### 10.255.10.0/24 1; 10.255.20.0/24 1; 10.255.30.0/24 1; 192.168.0.0/16 1; }
-
Map all the things...
Map module provides a more elegant solution for clearly parsing a big list of regexes, e.g. User-Agents.
map $http_user_agent $device_redirect { default "desktop"; ~(?i)ip(hone|od) "mobile"; ~(?i)android.*(mobile|mini) "mobile"; ~Mobile.+Firefox "mobile"; ~^HTC "mobile"; ~Fennec "mobile"; ~IEMobile "mobile"; ~BB10 "mobile"; ~SymbianOS.*AppleWebKit "mobile"; ~Opera\sMobi "mobile"; } if ($device_redirect = "mobile") { return 301 https://m.domain.com$request_uri; }
-
Drop the same root inside location block
If you add a root to every location block then a location block that isn’t matched will have no root. Set global
root
inside server directive.server { server_name domain.com; root /var/www/domain.com/public; location / { ... } location /api { ... } location /static { root /var/www/domain.com/static; ... } }
-
Use debug mode for debugging
There's probably more detail than you want, but that can sometimes be a lifesaver (but log file growing rapidly).
rewrite_log on; error_log /var/log/nginx/error-debug.log debug;
-
Set manually worker processes
The
worker_processes
directive is the sturdy spine of life for Nginx. This directive is responsible for letting our virtual server know many workers to spawn once it has become bound to the proper IP and port(s).For high load proxy servers (also standalone servers) the best value is ALL_CORES - 1 (please test it before used). Official Nginx documentation say: "When one is in doubt, setting it to the number of available CPU cores would be a good start (the value "auto" will try to autodetect it)."
# expr $(nproc --all) - 1 worker_processes 2;
-
Use HTTP/2
All requests are downloaded in parallel, not in a queue, HTTP headers are compressed, pages transfer as a binary, not as a text file, which is more efficient and more.
# For https: server { listen 10.240.20.2:443 ssl http2; ...
-
Maintaining SSL Sessions
This improves performance from the clients’ perspective, because it eliminates the need for a new (and time-consuming) SSL handshake to be conducted each time a request is made.
Most servers do not purge sessions or ticket keys, thus increasing the risk that a server compromise would leak data from previous (and future) connections.
ssl_session_cache shared:SSL:10m; ssl_session_timeout 24h; ssl_session_tickets off; ssl_buffer_size 1400;
-
Run as an unprivileged user
There is no real difference in security just by changing the process owner name. On the other hand in security, the principle of least privilege states that an entity should be given no more permission than necessary to accomplish its goals within a given system. This way only master process runs as root.
# Edit nginx.conf: user www-data; # Set owner and group: chown -R www-data:www-data /var/www/domain.com
-
Disable unnecessary modules
It is recommended to disable any modules which are not required as this will minimize the risk of any potential attacks by limiting the operations allowed by the web server.
# During installation: ./configure --without-http_autoindex_module # Comment modules in the configuration file: # load_module /usr/share/nginx/modules/ndk_http_module.so; # load_module /usr/share/nginx/modules/ngx_http_auth_pam_module.so;
-
Hide Nginx version number
Disclosing the version of nginx running can be undesirable, particularly in environments sensitive to information disclosure.
server_tokens off;
-
Hide Nginx server signature
You should compile Nginx from sources with
ngx_headers_more
to usedmore_set_headers
directive.more_set_headers "Server: Unknown";
-
Hide upstream proxy headers
When nginx is used to proxy requests from an upstream server (such as a PHP-FPM instance), it can be beneficial to hide certain headers sent in the upstream response (for example, the version of PHP running).
proxy_hide_header Server; proxy_hide_header X-Powered-By; proxy_hide_header X-AspNetMvc-Version; proxy_hide_header X-AspNet-Version; proxy_hide_header X-Drupal-Cache; proxy_hide_header Via; proxy_hide_header Link; proxy_hide_header X-Generator; proxy_hide_header X-Host; proxy_hide_header X-Url; proxy_hide_header Purge-Cache-Tags;
-
Keep only TLS 1.2 (+ TLS 1.3)
TLS 1.1 and 1.2 are both without security issues - but only v1.2 provides modern cryptographic algorithms. TLS 1.0 and TLS 1.1 protocols will be removed from browsers at the beginning of 2020.
ssl_protocols TLSv1.2;
-
Use only strong ciphers
This parameter changes quite often, the recommended configuration for today may be out of date tomorrow but remember - drop backward compatibility software components. Use only strong and not vulnerable ciphersuite.
ssl_ciphers "AES256+EECDH:AES256+EDH:!aNULL";
-
Use strong Key Exchange
Default key size in OpenSSL is
1024 bits
- it's vurnelable and breakable. For the best security configuration use4096 bit
DH Group or pre-configured DH groups from mozilla.# Generate DH Key: openssl dhparam -dsaparam -out /etc/nginx/ssl/dhparam_4096.pem 4096 # Nginx configuration: ssl_dhparam /etc/nginx/ssl/dhparams_4096.pem;
-
Use more secure ECDH Curve
X25519 is a more secure but slightly less compatible option. The NIST curves (prime256v1, secp384r1, secp521r1) are known to be weak and potentially vulnerable.
ssl_ecdh_curve X25519;
-
Defend against the BEAST attack
Enables server-side protection from BEAST attacks.
ssl_prefer_server_ciphers on;
-
Disable compression (mitigation of CRIME attack)
Disabling SSL/TLS compression stops the attack very effectively.
gzip off;
-
HTTP Strict Transport Security
The header indicates for how long a browser should unconditionally refuse to take part in unsecured HTTP connection for a specific domain.
add_header Strict-Transport-Security "max-age=15768000; includeSubdomains" always;
-
Reduce XSS risks (Content-Security-Policy)
CSP reduce the risk and impact of XSS attacks in modern browsers.
# This policy allows images, scripts, AJAX, and CSS from the same origin, and does not allow any other resources to load. add_header Content-Security-Policy "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';" always;
-
Control the behavior of the Referer header (Referrer-Policy)
Determine what information is sent along with the requests.
add_header Referrer-Policy "no-referrer";
-
Provide clickjacking protection (X-Frame-Options)
Helps to protect your visitors against clickjacking attacks. It is recommended that you use the x-frame-options header on pages which should not be allowed to render a page in a frame.
add_header X-Frame-Options "SAMEORIGIN" always;
-
Prevent some categories of XSS attacks (X-XSS-Protection)
Enable the cross-site scripting (XSS) filter built into modern web browsers.
add_header X-XSS-Protection "1; mode=block" always
-
Prevent Sniff Mimetype middleware (X-Content-Type-Options)
It prevents the browser from doing MIME-type sniffing (prevents "mime" based attacks).
add_header X-Content-Type-Options "nosniff" always;
-
Reject unsafe HTTP methods
Set of methods support by a resource. An ordinary web server supports the HEAD, GET and POST methods to retrieve static and dynamic content. Other (e.g. OPTIONS, TRACE) methods should not be supported on public web servers, as they increase the attack surface.
add_header Allow "GET, POST, HEAD" always; if ( $request_method !~ ^(GET|POST|HEAD)$ ) { return 405; }
-
Control Buffer Overflow attacks
Buffer overflow attacks are made possible by writing data to a buffer and exceeding that buffers’ boundary and overwriting memory fragments of a process. To prevent this in nginx we can set buffer size limitations for all clients.
client_body_buffer_size 100k; client_header_buffer_size 1k; client_max_body_size 100k; large_client_header_buffers 2 1k;
-
Mitigating Slow HTTP DoS attack (Closing Slow Connections)
Close connections that are writing data too infrequently, which can represent an attempt to keep connections open as long as possible.
client_body_timeout 10s; client_header_timeout 10s; keepalive_timeout 5 5; send_timeout 10;