The Nginx Server Guide

December 9, 2022
:79  :0

Nginx (engine x) is a high-performance HTTP server and reverse proxy that also functions as a mail proxy and load balancer. Renowned for its high concurrency handling, reliability, and low memory footprint, it powers 34% of all web servers globally (Netcraft Survey 2024).


Installation Guide

Linux Systems

# Ubuntu/Debian
sudo apt update && sudo apt install nginx -y

# CentOS/RHEL
sudo yum install epel-release && sudo yum install nginx

# Verify installation
nginx -v  # Should display version e.g. nginx/1.25.3

macOS (Homebrew)

brew install nginx
brew services start nginx

Windows

  1. Download from nginx.org
  2. Unzip and run nginx.exe

Production Note: Windows support is limited - recommended for development only.


Core Configuration Architecture

Nginx's main configuration file (/etc/nginx/nginx.conf) follows this structure:

user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;

events {
    worker_connections 1024;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    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;
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65;
    
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Essential Configuration Templates

1. Static Website Hosting

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    
    location / {
        try_files $uri $uri/ =404;
        expires 30d;
        add_header Cache-Control "public";
    }
    
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        access_log off;
    }
}

2. Reverse Proxy Setup

server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # Timeout settings
        proxy_connect_timeout 60s;
        proxy_read_timeout 90s;
    }
}

3. Load Balancing Configuration

upstream backend {
    least_conn;  # Load balancing method
    server 10.0.0.1:8000 weight=3;
    server 10.0.0.2:8000;
    server 10.0.0.3:8000 backup;
}

server {
    listen 80;
    server_name app.example.com;
    
    location / {
        proxy_pass http://backend;
        include proxy_params;
    }
}

4. HTTPS with Let's Encrypt

# Obtain certificate (Ubuntu)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

Auto-renewal setup:

sudo crontab -e
# Add line:
0 12 * * * /usr/bin/certbot renew --quiet

Advanced Configurations

Security Headers

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";

Rate Limiting

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/m;

server {
    location /api/ {
        limit_req zone=api_limit burst=50 nodelay;
        proxy_pass http://api_backend;
    }
}

Performance Optimizations

# Enable gzip compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_types text/plain text/css application/json application/javascript text/xml;

# Cache optimization
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;

Management Commands

ActionCommand
Startsudo systemctl start nginx
Stopsudo systemctl stop nginx
Restartsudo systemctl restart nginx
Reload (no downtime)sudo systemctl reload nginx
Test configsudo nginx -t
Check statussudo systemctl status nginx

Troubleshooting Guide

Common Issues

  1. Port 80 already in use:

    sudo lsof -i :80
    sudo kill <PID>
    
  2. Permission denied:

    sudo chown -R www-data:www-data /var/www
    sudo chmod -R 755 /var/www
    
  3. SSL certificate errors:

    sudo certbot renew --dry-run
    

Log Analysis

# Real-time error monitoring
tail -f /var/log/nginx/error.log

# Top client IPs
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -n 10

Performance Benchmarking

Test your Nginx configuration with:

# Install benchmark tool
sudo apt install apache2-utils

# Run test (adjust parameters)
ab -n 10000 -c 500 http://yourserver/

Expected performance on 2GB VM:

  • Static files: ~8,000 req/sec
  • Reverse proxy: ~3,000 req/sec
  • HTTPS: ~1,500 req/sec

More Learning Resources

  1. Nginx Official Docs
  2. DigitalOcean Nginx Tutorials
  3. Nginx Config Generator

Pro Tip: For production environments, consider using Ansible or Terraform to manage Nginx configurations across servers.