2024-08-27
Configure NGINX for web serving, load balancing, reverse proxy, caching, and security in production environments.
NGINX is a high-performance HTTP server, reverse proxy, and load balancer. This comprehensive guide covers NGINX configuration, optimization techniques, security hardening, and advanced features for production deployments.
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 2048;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
# Performance
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json
application/javascript text/xml application/xml;
include /etc/nginx/conf.d/*.conf;
}
# /etc/nginx/conf.d/example.com.conf
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
# Redirect to HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;
# SSL configuration
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# Security headers
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
# Static assets caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}
upstream nodejs_backend {
least_conn;
server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
server 127.0.0.1:3001 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://nodejs_backend;
proxy_http_version 1.1;
# Headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Buffering
proxy_buffering off;
proxy_cache_bypass $http_upgrade;
}
# WebSocket support
location /ws {
proxy_pass http://nodejs_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Round Robin (default)
Distributes requests evenly
Least Connections
Routes to server with fewest connections
IP Hash
Client IP determines server
Weighted
Distribute based on server weights
# Proxy cache configuration
proxy_cache_path /var/cache/nginx levels=1:2
keys_zone=api_cache:10m max_size=1g
inactive=60m use_temp_path=off;
server {
location /api {
# Enable caching
proxy_cache api_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
# Cache successful responses for 10 minutes
proxy_cache_valid 200 10m;
proxy_cache_valid 404 1m;
# Cache bypass conditions
proxy_cache_bypass $http_cache_control;
proxy_no_cache $http_cache_control;
# Add cache status header
add_header X-Cache-Status $upstream_cache_status;
# Use stale cache during updates
proxy_cache_use_stale error timeout updating
http_500 http_502 http_503;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_pass http://backend;
}
# Purge cache endpoint
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge api_cache "$scheme$request_method$host$1";
}
}
# Define rate limit zones
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
# API rate limiting
location /api {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# Login rate limiting
location /login {
limit_req zone=login burst=5;
proxy_pass http://backend;
}
# Connection limiting
limit_conn addr 10;
}
# IP whitelisting
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
proxy_pass http://backend;
}
# Basic authentication
location /private {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
# Block malicious requests
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|OPTIONS)$) {
return 405;
}
if ($http_user_agent ~* (bot|crawler|spider)) {
return 403;
}
Worker Tuning
Set worker_processes to auto and adjust worker_connections based on expected traffic.
Enable HTTP/2
Use HTTP/2 for improved performance with multiplexing and server push capabilities.
Optimize Buffers
Tune client_body_buffer_size and client_header_buffer_size based on your application needs.
Use FastCGI Cache
Enable FastCGI caching for PHP applications to reduce backend load.
Published on 2024-08-27 • Category: DevOps
← Back to BlogFree online developer tools and utilities for encoding, formatting, generating, and analyzing data. No registration required - all tools work directly in your browser.
Built for developers, by developers. Privacy-focused and open source.
Free online tools for Base64 encoding, JSON formatting, URL encoding, hash generation, UUID creation, QR codes, JWT decoding, timestamp conversion, regex testing, and more.
© 2024 NarvikHub. All rights reserved.