Nginx
Chapter 67: Nginx Web Server
Section titled “Chapter 67: Nginx Web Server”High-Performance Web Server and Reverse Proxy
Section titled “High-Performance Web Server and Reverse Proxy”67.1 Understanding Nginx Architecture
Section titled “67.1 Understanding Nginx Architecture”How Nginx Works
Section titled “How Nginx Works”Nginx (pronounced “engine-x”) is a high-performance HTTP server, reverse proxy, and load balancer. Its event-driven, non-blocking architecture makes it extremely efficient at handling concurrent connections.
Nginx Architecture+------------------------------------------------------------------+| || Nginx Process Model || || +-------------------------------------------------------------+|| | Master Process (PID 1) ||| | +----------------------------------------------------------+ || | | - Reads and validates configuration | || | | - Creates worker processes | || | | - Binds to ports 80/443 | || | | - Manages workers (reload, quit) | || | | - Handles signals (QUIT, HUP, USR1, TERM) | || | +----------------------------------------------------------+ || +-------------------------------------------------------------+| | || v || +-------------------------------------------------------------+|| | Worker Processes ||| | +----------------------------------------------------------+ || | | Worker Process 1 Worker Process 2 Worker N | || | | +--------------------+ +--------------------+ | || | | | Event Loop | | Event Loop | | || | | | +----------------+ | | +----------------+ | | || | | | | epoll/kqueue | | | | epoll/kqueue | | | || | | | | - accept() | | | | - accept() | | | || | | | | - read() | | | | - read() | | | || | | | | - write() | | | | - write() | | | || | | | | - sendfile() | | | | - sendfile() | | | || | | | +----------------+ | | +----------------+ | | || | | +--------------------+ +--------------------+ | || | +----------------------------------------------------------+ || | Each worker handles thousands of concurrent connections || +-------------------------------------------------------------+| || Event-Driven, Non-Blocking Architecture: || +----------------------------------------------------------+ || | 1. Master creates sockets on ports 80/443 | || | 2. Workers accept connections (via epoll/kqueue) | || | 3. Each connection is handled asynchronously | || | 4. Worker can handle 10,000+ connections (one thread) | || | 5. No process/thread per connection overhead | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Installation
Section titled “Installation”# Debian/Ubuntusudo apt updatesudo apt install nginxsudo apt install nginx-extras # Extra modules
# RHEL/CentOS/Fedorasudo dnf install nginxsudo yum install epel-releasesudo yum install nginx
# Arch Linuxsudo pacman -S nginxsudo pacman -S nginx-mainline # Latest version
# From source (with custom modules)wget http://nginx.org/download/nginx-1.24.0.tar.gztar -xzf nginx-1.24.0.tar.gzcd nginx-1.24.0./configure --with-http_ssl_module --with-http_v2_modulemakesudo make install
# Start/stop/restartsudo systemctl start nginxsudo systemctl stop nginxsudo systemctl restart nginxsudo systemctl reload nginx # Graceful reloadsudo systemctl status nginx
# Enable on bootsudo systemctl enable nginx67.2 Nginx Configuration Structure
Section titled “67.2 Nginx Configuration Structure”Main Configuration File
Section titled “Main Configuration File” Nginx Configuration Hierarchy+------------------------------------------------------------------+| || /etc/nginx/ || ├── nginx.conf # Main config || ├── conf.d/ # Additional configs │| │ └── *.conf # Server blocks │| ├── sites-enabled/ # Enabled sites (symlinks) │| │ ├── default # Default site │| │ └── example.com # Your site │| ├── sites-available/ # Available sites │| │ ├── default # Default site │| │ └── example.com # Your site │| ├── modules-enabled/ # Enabled modules │| ├── modules-available/ # Available modules │| ├── snippets/ # Reusable config snippets │| ├── mime.types # MIME types || └── fastcgi_params # FastCGI parameters || || Configuration File Syntax: || +----------------------------------------------------------+ || | Directives end with semicolon (;) | || | Blocks are enclosed in braces { } | || | Comments start with # | || | Includes use include directive | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Core nginx.conf
Section titled “Core nginx.conf”# User and group (defaults to nobody/nobody if omitted)user www-data;worker_processes auto; # auto = number of CPU coresworker_rlimit_nofile 65535; # max files per workerpid /run/nginx.pid;error_log /var/log/nginx/error.log;
# Load dynamic modulesinclude /etc/nginx/modules-enabled/*.conf;
events { worker_connections 4096; # Max connections per worker use epoll; # Linux-specific (most efficient) multi_accept on; # Accept multiple connections}
http { # Basic Settings sendfile on; tcp_nopush on; # Optimize packet sending tcp_nodelay on; # Disable Nagle's algorithm keepalive_timeout 65; keepalive_requests 10000; types_hash_max_size 2048;
# Server names hash server_names_hash_bucket_size 64; client_max_body_size 16M;
# Include MIME types include /etc/nginx/mime.types; default_type application/octet-stream;
# Logging Settings log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
# Gzip Settings gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_min_length 1024; gzip_types text/plain text/css text/xml application/json application/javascript application/xml application/xml+rss;
# Buffer settings client_body_buffer_size 128k; client_header_buffer_size 1k; large_client_header_buffers 4 16k;
# Timeouts client_body_timeout 12; client_header_timeout 12; send_timeout 10;
# Rate limiting zone limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
# Connection limiting limit_conn_zone $binary_remote_addr zone=addr:10m;
# Virtual Host Configs include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;}67.3 Server Blocks and Locations
Section titled “67.3 Server Blocks and Locations”Basic Server Block
Section titled “Basic Server Block”server { listen 80; listen [::]:80; server_name example.com www.example.com;
# Document root root /var/www/example.com/html; index index.html index.htm index.php;
# Logging access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log;
# Default location location / { try_files $uri $uri/ =404; }
# Error pages error_page 404 /404.html; error_page 500 502 503 504 /50x.html;
# Deny access to hidden files location ~ /\. { deny all; access_log off; log_not_found off; }}Location Block Matching
Section titled “Location Block Matching” Nginx Location Matching+------------------------------------------------------------------+| || Matching order (first match wins): || || 1. Exact match: location = /path || = / exact match only || || 2. Prefix match: location /path || /path matches /path, /path/, /path/file || Longer prefix wins || || 3. Regex match: location ~ /path || ~ case-sensitive regex || ~* case-insensitive regex || ^~ stops matching if matched || || 4. Named locations: location @name || Used for internal redirects || || Examples: || +----------------------------------------------------------+ || | location = / | Exact match for / | || | location / | Matches everything | || | location /images/ | Images directory | || | location ~ \.php$ | PHP files (regex) | || | location ~* \.php$ | PHP files (case-insensitive) | || | location ^~ /api/ | Stop regex, use prefix match | || | location @backend | Named location for internal use | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Common Location Directives
Section titled “Common Location Directives”server { # Root location location / { root /var/www/html; index index.html index.htm; try_files $uri $uri/ =404; }
# Alias location location /images/ { alias /var/www/images/; autoindex on; # Directory listing }
# Named location for internal redirects location / { try_files $uri $uri/ @backend; }
location @backend { proxy_pass http://backend-server; }
# Regex location (case-sensitive) location ~ \.php$ { fastcgi_pass unix:/run/php/php-fpm.sock; fastcgi_index index.php; include fastcgi_params; }
# Case-insensitive regex location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, immutable"; }
# Block specific patterns location ~ /\.(?!well-known).* { deny all; }
# IP-based access location /admin/ { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; }}67.4 Reverse Proxy Configuration
Section titled “67.4 Reverse Proxy Configuration”Basic Reverse Proxy
Section titled “Basic Reverse Proxy”server { listen 80; server_name api.example.com;
location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1;
# Headers 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 on; proxy_buffer_size 4k; proxy_buffers 8 16k; proxy_busy_buffers_size 24k; }}Advanced Reverse Proxy Options
Section titled “Advanced Reverse Proxy Options”location / { proxy_pass http://backend; proxy_http_version 1.1;
# Essential headers 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; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port;
# Connection upgrade (for WebSocket) proxy_set_header Connection "";
# For WebSocket proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";
# Timeouts proxy_connect_timeout 30s; proxy_send_timeout 30s; proxy_read_timeout 30s;
# Buffers proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k;
# Errors proxy_intercept_errors off; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
# SSL (if backend is HTTPS) # proxy_ssl_server_name on; # proxy_ssl_verify on; # proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;}67.5 Load Balancing
Section titled “67.5 Load Balancing”Upstream Configuration
Section titled “Upstream Configuration”# Define upstream serversupstream backend_servers { least_conn; # Load balancing method
# Server with weight server 10.0.0.1:8080 weight=5; server 10.0.0.2:8080 weight=3; server 10.0.0.3:8080;
# Backup servers (only used when others fail) server 10.0.0.4:8080 backup; server 10.0.0.5:8080 backup;
# Down server (marked as down) server 10.0.0.6:8080 down;
# Keepalive connections keepalive 32;}
# Using the upstreamserver { location / { proxy_pass http://backend_servers;
# Health check (basic) proxy_connect_timeout 5s; proxy_next_upstream error timeout http_502; }}Load Balancing Methods
Section titled “Load Balancing Methods” Load Balancing Methods+------------------------------------------------------------------+| || Method | Description || -------------------|--------------------------------------------|| round_robin | Default, requests distributed evenly || least_conn | Fewest active connections || ip_hash | Same IP to same server (sessions) || hash | Custom hash (e.g., $request_uri) || least_time | Fastest response time (ngx_http_upstream | || | _module) || random | Random with optional weights || || Configuration Examples: || +----------------------------------------------------------+ || | ip_hash; # Sticky sessions | || | least_conn; # Reduced load on busy servers | || | hash $cookie_session_id; # Session affinity | || | random two; # Two random servers | || +----------------------------------------------------------+ || || Server Options: || +----------------------------------------------------------+ || | weight=N | Relative weight (default 1) | || | max_fails=N | Failures before marking down (1) | || | fail_timeout=N | Time to consider server failed (10s)| || | backup | Backup server (only when others down) | || | down | Mark as down (not used) | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Complete Load Balancer Example
Section titled “Complete Load Balancer Example”upstream api_backend { least_conn;
server 10.0.1.10:8000 weight=3 max_fails=3 fail_timeout=30s; server 10.0.1.11:8000 weight=3 max_fails=3 fail_timeout=30s; server 10.0.1.12:8000 weight=2 max_fails=3 fail_timeout=30s; server 10.0.1.13:8000 backup;
keepalive 64;}
server { listen 80; server_name api.example.com;
# Rate limiting limit_req zone=api_limit burst=20 nodelay; limit_conn addr 10;
location / { proxy_pass http://api_backend;
proxy_http_version 1.1; 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;
# Connection pooling proxy_set_header Connection "";
# Timeouts proxy_connect_timeout 10s; proxy_send_timeout 30s; proxy_read_timeout 30s;
# Error handling proxy_next_upstream error timeout http_502 http_503 http_504; proxy_intercept_errors off; }
# Health check endpoint location /health { access_log off; return 200 "healthy\n"; add_header Content-Type text/plain; }}67.6 SSL/TLS Configuration
Section titled “67.6 SSL/TLS Configuration”SSL Certificate Setup
Section titled “SSL Certificate Setup”server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com;
# SSL Certificate ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL Configuration ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off;
# Modern SSL configuration (Mozilla Intermediate) ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
# OCSP Stapling ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s;
# Session caching ssl_session_timeout 1d; ssl_session_cache shared:SSL:10m; ssl_session_tickets off;
# HSTS (optional but recommended) add_header Strict-Transport-Security "max-age=63072000" always;
# Additional security headers add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Redirect HTTP to HTTPS location / { root /var/www/html; try_files $uri $uri/ =404; }}
# HTTP to HTTPS redirectserver { listen 80; listen [::]:80; server_name example.com www.example.com;
location / { return 301 https://$host$request_uri; }
# ACME challenge for Let's Encrypt location /.well-known/acme-challenge/ { root /var/www/html; }}SSL Configuration Best Practices
Section titled “SSL Configuration Best Practices” SSL/TLS Best Practices+------------------------------------------------------------------+| || Protocol Settings: || +----------------------------------------------------------+ || | ssl_protocols TLSv1.2 TLSv1.3; (disable TLSv1, TLSv1.1)| || +----------------------------------------------------------+ || || Cipher Suites: || +----------------------------------------------------------+ || | Mozilla Intermediate: | || | ECDHE-ECDSA-AES128-GCM-SHA256 | || | ECDHE-RSA-AES128-GCM-SHA256 | || | ECDHE-ECDSA-AES256-GCM-SHA384 | || | ECDHE-RSA-AES256-GCM-SHA384 | || | | || | Mozilla Modern (TLSv1.3 only): | || | TLS_AES_256_GCM_SHA384 | || | TLS_CHACHA20_POLY1305_SHA256 | || +----------------------------------------------------------+ || || Security Headers: || +----------------------------------------------------------+ || | Strict-Transport-Security: max-age=63072000 | || | X-Frame-Options: SAMEORIGIN | || | X-Content-Type-Options: nosniff | || | X-XSS-Protection: 1; mode=block | || | Referrer-Policy: strict-origin-when-cross-origin | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+67.7 Performance Optimization
Section titled “67.7 Performance Optimization”Worker Process Tuning
Section titled “Worker Process Tuning”# Master process settingsuser www-data;worker_processes auto; # Match CPU coresworker_rlimit_nofile 65535; # File descriptors
events { worker_connections 4096; # Per worker use epoll; # Linux epoll multi_accept on; # Accept many at once}
# Multi-accept: worker accepts multiple connections at once# epoll: Linux-specific event model (most efficient)# kqueue: BSD/macOS# poll: PortableHTTP Optimization
Section titled “HTTP Optimization”http { # Sendfile - kernel-level file transfer sendfile on;
# TCP optimizations tcp_nopush on; # Send headers in one packet tcp_nodelay on; # Disable Nagle's algorithm
# Keep-alive keepalive_timeout 65; keepalive_requests 10000;
# Gzip compression gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# Caching open_file_cache max=10000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;
# Buffers client_body_buffer_size 128k; client_max_body_size 20M;
# Static file serving aio on; sendfile_max_chunk 512k;}FastCGI (PHP) Optimization
Section titled “FastCGI (PHP) Optimization”location ~ \.php$ { fastcgi_pass unix:/run/php/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params;
# FastCGI timeouts fastcgi_connect_timeout 60s; fastcgi_send_timeout 60s; fastcgi_read_timeout 60s;
# Buffers fastcgi_buffer_size 32k; fastcgi_buffers 8 16k; fastcgi_busy_buffers_size 64k;
# Caching fastcgi_cache_path /var/cache/nginx/fpm levels=1:2 keys_zone=fpm_cache:10m max_size=1g inactive=60m; fastcgi_cache_key "$scheme$request_method$host$request_uri"; fastcgi_cache_valid 200 302 10m; fastcgi_cache_valid 404 1m; fastcgi_cache_use_stale error timeout updating http_500 http_502 http_503; fastcgi_cache_background_update on; fastcgi_cache_lock on;
add_header X-FastCGI-Cache $upstream_cache_status;}67.8 Rate Limiting
Section titled “67.8 Rate Limiting”Rate Limiting Configuration
Section titled “Rate Limiting Configuration”http { # Define rate limit zones limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s; limit_req_zone $binary_remote_addr zone=login:10m rate=3r/s; limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s; limit_conn_zone $binary_remote_addr zone=addr:10m;
server { # General rate limiting location / { limit_req zone=general burst=20 nodelay; limit_conn addr 10; }
# Login endpoints (stricter) location /login { limit_req zone=login burst=5 nodelay; }
# API endpoints location /api/ { limit_req zone=api burst=50 nodelay; }
# Bypass for specific IPs location /health { limit_req zone=general off; } }}67.9 Caching Configuration
Section titled “67.9 Caching Configuration”Proxy Caching
Section titled “Proxy Caching”http { # Proxy cache path proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=api_cache:100m max_size=10g inactive=60m use_temp_path=off;
# FastCGI cache path fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:100m max_size=10g inactive=60m;
server { # Enable proxy caching location / { proxy_pass http://backend;
# Cache key proxy_cache_key "$scheme$host$request_uri";
# Cache rules proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_valid any 1m;
# Cache control proxy_cache_use_stale error timeout updating http_500 http_502 http_503; proxy_cache_background_update on; proxy_cache_lock on;
# Headers add_header X-Cache-Status $upstream_cache_status;
# Bypass cache # Set-Cookie: nocache=1 proxy_cache_bypass $http_cookie;
# Don't cache proxy_no_cache $http_pragma $http_authorization; }
# Static files - aggressive caching location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf)$ { expires 30d; add_header Cache-Control "public, immutable"; access_log off; } }}67.10 Security Configuration
Section titled “67.10 Security Configuration”Security Hardening
Section titled “Security Hardening”server { # Hide nginx version server_tokens off;
# Hide upstream headers proxy_hide_header X-Powered-By; proxy_hide_header X-AspNet-Version; fastcgi_hide_header X-Powered-By;
# Additional security headers add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Content-Security-Policy "default-src 'self'" always;
# IP-based access control location /admin/ { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all;
# Basic auth auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.htpasswd; }
# Block common exploits location ~ /\.(svn|git|hg) { deny all; }
location ~* \.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)$ { deny all; }
location ~* /(?:uploads|files)/.*\.php$ { deny all; }}67.11 Troubleshooting Nginx
Section titled “67.11 Troubleshooting Nginx”Common Commands
Section titled “Common Commands”# Test configurationnginx -t # Test and report errorsnginx -T # Test and show full confignginx -v # Show versionnginx -V # Show version and modules
# Reload configurationnginx -s reload # Graceful reloadnginx -s reopen # Reopen log filesnginx -s stop # Stop immediatelynginx -s quit # Graceful shutdown
# Check running configcat /proc/$(pgrep nginx)/cmdline | tr '\0' '\n'
# View error logtail -f /var/log/nginx/error.log
# Check open fileslsof -i :80ss -tlnp | grep nginx
# Process informationps aux | grep nginxps -ef | grep nginxCommon Issues and Solutions
Section titled “Common Issues and Solutions”# 1. Permission denied# Check file/directory permissionsls -la /var/www/# Fix: chmod 755 /var/www, chmod 644 files
# 2. Too many open files# Check ulimitulimit -n# Fix in /etc/nginx/nginx.conf: worker_rlimit_nofile 65535# Fix in /etc/security/limits.conf
# 3. Upstream timed out# Increase timeouts# Check backend is responding
# 4. 502 Bad Gateway# Check PHP-FPM is runningsystemctl status php-fpm# Check socket permissions
# 5. 504 Gateway Timeout# Increase proxy timeouts# Check backend performance
# 6. SSL errors# Check certificate pathsopenssl x509 -in /path/to/cert -text -noout# Verify certificate matches domain67.12 Interview Questions
Section titled “67.12 Interview Questions”Basic Questions
Section titled “Basic Questions”-
What is Nginx and how does it differ from Apache?
- Nginx is an event-driven, non-blocking server; Apache is process-based
-
What is the default port for HTTP and HTTPS?
- 80 for HTTP, 443 for HTTPS
-
How do you test Nginx configuration?
nginx -t
-
What does worker_processes auto do?
- Automatically sets number of worker processes to match CPU cores
-
What is a server block in Nginx?
- Virtual host configuration for a domain
Intermediate Questions
Section titled “Intermediate Questions”-
Explain the difference between proxy_pass and fastcgi_pass
- proxy_pass: reverse proxy to HTTP backend
- fastcgi_pass: connect to PHP-FPM or FastCGI server
-
How does Nginx handle load balancing?
- Uses upstream blocks with methods: round_robin, least_conn, ip_hash
-
What is the purpose of try_files?
- Check if files exist in order, fallback to named location or error
-
How do you enable SSL in Nginx?
- Listen on 443 ssl, specify certificate and key files
-
What is upstream in Nginx?
- Defines backend servers for load balancing
Advanced Questions
Section titled “Advanced Questions”-
Explain Nginx event-driven architecture
- Single worker handles many connections via epoll/kqueue
-
How do you optimize Nginx for high traffic?
- worker_processes auto, worker_connections, sendfile, tcp_nopush, gzip, caching
-
What is the difference between location ~ and location ~*?
- ~ is case-sensitive regex, ~* is case-insensitive
-
How does rate limiting work in Nginx?
- Uses limit_req_zone and limit_req directives
-
Explain the Nginx config hierarchy
- nginx.conf → conf.d/.conf → sites-enabled/
Summary
Section titled “Summary”Nginx is a powerful, high-performance web server and reverse proxy:
Quick Reference+------------------------------------------------------------------+| || Essential Commands: || +----------------------------------------------------------+ || | nginx -t | Test configuration | || | nginx -s reload | Graceful reload | || | nginx -s stop | Stop | || | systemctl status nginx | Check status | || +----------------------------------------------------------+ || || Key Directives: || +----------------------------------------------------------+ || | server {} | Virtual host | || | location {} | URL matching | || | proxy_pass | Reverse proxy | || | upstream {} | Backend servers | || | try_files | File checking | || | rewrite | URL rewriting | || | return | Direct response | || +----------------------------------------------------------+ || || Performance Tips: || +----------------------------------------------------------+ || | worker_processes auto | Match CPU cores | || | worker_connections 4096 | Connections per worker | || | sendfile on | Kernel file transfer | || | gzip on | Compression | || | keepalive for upstream | Connection pooling | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+