Deep Dive on NGINX Directives
NGINX directives—from the basic to the advanced—with practical examples, recommended default values, and production tips.
NGINX’s flexibility comes from its rich set of configuration directives. In production, understanding these directives can help fine-tune performance, security, and resource management.
1. Global and Core Directives
worker_processes
Purpose: Defines the number of worker processes. , the default value is 1.
Example:
worker_processes auto;
Production Tip: Use auto, as this ensures efficient utilization of system resources to match available CPU cores.
error_log
Purpose: Specifies the file where errors are logged.
Example:
error_log /var/log/nginx/error.log warn;
Default/Recommended: Default is usually
error.log
in the installation directory; using a log level likewarn
orerror
is ideal for production. Use debug for issues.
include
Purpose: Allows you to include additional configuration files.
Example:
include /etc/nginx/conf.d/*.conf;
Production Tip: Modularize configurations for maintainability.
2. Events Block Directives
worker_connections
Purpose: Sets the maximum number of simultaneous connections per worker.
Example:
events { worker_connections 1024; }
Default/Recommended: Default is often 512 or 1024; adjust based on traffic.
Production Tip: A higher value can help handle heavy loads, but ensure the OS limits are adjusted accordingly.
multi_accept
Purpose: Allows a worker to accept all new connections at once.
Example:
events { multi_accept on; }
Production Tip: Helps reduce latency under high connection rates.
3. HTTP Block Directives
include (HTTP Context)
Purpose: Include MIME types and other HTTP-level configs.
Example:
http { include mime.types; default_type application/octet-stream; }
Production Tip: Keep MIME types updated to ensure proper file delivery.
sendfile, tcp_nodelay, tcp_nopush
Purpose: Optimize file transfers.
Example:
http { sendfile on; tcp_nodelay on; tcp_nopush on; }
Production Tip: These settings minimize latency and maximize throughput for static files.
keepalive_timeout
Purpose: Defines the timeout for persistent connections.
Example:
http { keepalive_timeout 65; }
Default/Recommended: The default is usually 75 seconds; 65 seconds is a common production setting.
client_max_body_size
Purpose: Limits the size of client request bodies.
Example:
http { client_max_body_size 16M; }
Production Tip: Set a sensible limit based on your application’s needs to mitigate DoS risks.
4. Server and Location Block Directives
listen and server_name
Purpose: Bind virtual hosts to specific IPs/ports and domain names.
Example:
server { listen 80; server_name example.com www.example.com; }
Production Tip: Use precise names and ports to avoid ambiguity in multi-tenant environments.
root and index
Purpose: Define where static files are served from.
Example:
server { root /var/www/html; index index.html index.htm; }
Production Tip: Ensure file paths match your deployment structure to prevent 404s.
error_page
Purpose: Customize responses for error codes.
Example:
server { error_page 404 /custom_404.html; location = /custom_404.html { internal; } }
Production Tip: Custom error pages enhance user experience and can hide sensitive server information.
5. URI Processing Directives
location
Purpose: Handle requests based on URI patterns.
Example:
server { location /static/ { root /var/www; } }
Production Tip: Combine exact (
location =
), prefix, and regex-based locations carefully to avoid unexpected matches.
rewrite
Purpose: Change request URIs using regex.
Example:
server { location /old/ { rewrite ^/old/(.*)$ /new/$1 permanent; } }
Production Tip: Use permanent redirects (
301
) only when URLs have permanently changed.
try_files
Purpose: Check for the existence of files before proxying or handling errors.
Example:
server { location / { try_files $uri $uri/ /index.html; } }
Production Tip: Use
try_files
to efficiently serve static content and reduce backend load.
6. Proxying and Upstream Directives
proxy_pass
Purpose: Forward requests to a backend server or upstream group.
Example:
server { location /api/ { proxy_pass http://backend_servers; } }
Production Tip: Ensure you correctly forward headers using additional directives (e.g.,
proxy_set_header
) for proper client IP logging and security.
upstream
Purpose: Define groups of backend servers for load balancing.
Example:
upstream backend_servers { server backend1.example.com weight=2; server backend2.example.com; }
Production Tip: Configure health checks and use weighted balancing to distribute load evenly.
proxy_set_header
Purpose: Modify or add headers when proxying.
Example:
location /api/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://backend_servers; }
Production Tip: Proper header forwarding is crucial for security and logging.
proxy_redirect
Purpose: Modify the “Location” header in responses from proxied servers.
Example:
location /api/ { proxy_pass http://backend_servers; proxy_redirect off; }
Production Tip: Adjust proxy redirects to maintain client-side URL consistency.
7. FastCGI, SCGI, and uWSGI Directives
fastcgi_pass and fastcgi_param
Purpose: Forward requests to FastCGI application servers.
Example:
location ~ \.php$ { fastcgi_pass unix:/run/php/php7.4-fpm.sock; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }
Production Tip: Ensure file paths and socket settings are correct; secure your FastCGI interface to prevent unauthorized access.
8. Caching and Compression Directives
proxy_cache_path and proxy_cache
Purpose: Configure caching for proxied content.
Example:
http { proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off; server { location / { proxy_cache my_cache; proxy_pass http://backend_servers; } } }
Production Tip: Monitor cache performance and configure proper expiration policies.
gzip
Purpose: Enable response compression.
Example:
http { gzip on; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript; }
Production Tip: Tweak
gzip_min_length
andgzip_types
to balance CPU usage and bandwidth savings.
9. Security and Advanced Directives
SSL/TLS Directives
ssl_certificate and ssl_certificate_key
Purpose: Define the SSL certificate and key for secure connections.
Example:
server { listen 443 ssl; ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; }
Production Tip: Use automated certificate renewal and strong ciphers.
allow and deny
Purpose: Restrict access based on IP addresses.
Example:
location /admin/ { allow 192.168.1.0/24; deny all; }
Production Tip: Implement IP whitelisting for sensitive resources.
auth_basic
Purpose: Enable HTTP basic authentication.
Example:
location /secure/ { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; }
Production Tip: For stronger security, integrate with external authentication providers.
resolver
Purpose: Specify DNS servers for resolving domain names (useful for dynamic or upstream configurations).
Example:
http { resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s; }
Default/Recommended: If not set, NGINX falls back to the system resolver. In production, explicitly setting resolvers (for example, Google DNS) improves reliability when using domain names in upstream blocks.
Production Tip: Use a short
resolver_timeout
to avoid delays, and update the DNS list as needed.
client_body_timeout and client_header_timeout
Purpose: Define timeouts for reading client request bodies and headers.
Example:
http { client_body_timeout 12; client_header_timeout 12; }
Production Tip: Shorten timeouts to mitigate slow client attacks while avoiding premature termination for legitimate users.
Last updated