# ============================================================================
# Nginx Load Balancer Configuration
# For distributing traffic across multiple backend servers
# Standards: 2025 Security Best Practices with High Availability
# ============================================================================

# Rate Limiting Zones
# Place in http block of /etc/nginx/nginx.conf if not already present
limit_req_zone $binary_remote_addr zone=general:10m rate=20r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

# ============================================================================
# Upstream Configuration (Backend Servers)
# ============================================================================

upstream backend {
    # Load Balancing Method
    # Options: round-robin (default), least_conn, ip_hash, hash, random
    least_conn;  # Route to server with fewest active connections

    # Backend Servers
    # Format: server <address>:<port> [parameters]
    # CUSTOMIZE THESE - Replace with your actual backend servers
    server backend1.example.com:8080 max_fails=3 fail_timeout=30s weight=1;
    server backend2.example.com:8080 max_fails=3 fail_timeout=30s weight=1;
    server backend3.example.com:8080 max_fails=3 fail_timeout=30s weight=1;

    # Backup server (used only when all primary servers are down)
    # server backend4.example.com:8080 backup;

    # Connection Pooling (improves performance)
    keepalive 32;
    keepalive_requests 100;
    keepalive_timeout 60s;
}

# Optional: Separate upstream for health checks or admin endpoints
upstream backend_admin {
    server backend1.example.com:9090;
    server backend2.example.com:9090;
    server backend3.example.com:9090;
}

# ============================================================================
# HTTP to HTTPS Redirect
# ============================================================================

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    # Let's Encrypt challenge
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    # Redirect all HTTP to HTTPS
    location / {
        return 301 https://$server_name$request_uri;
    }
}

# ============================================================================
# HTTPS Load Balancer Server Block
# ============================================================================

server {
    # Listen on port 443 with HTTP/2 support
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # Server name
    server_name example.com www.example.com;

    # ========================================================================
    # SSL/TLS Configuration (2025 Standards)
    # ========================================================================

    # Certificate paths - CUSTOMIZE THESE
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    # Modern protocols only (TLS 1.2 and 1.3)
    ssl_protocols TLSv1.2 TLSv1.3;

    # Session settings
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;

    # Let client choose cipher (recommended for TLS 1.3)
    ssl_prefer_server_ciphers off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/ssl/certs/ca-bundle.crt;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    # ========================================================================
    # Security Headers
    # ========================================================================

    # Hide Nginx version
    server_tokens off;

    # HSTS (1 year with includeSubDomains and preload)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # Prevent clickjacking
    add_header X-Frame-Options "SAMEORIGIN" always;

    # Prevent MIME sniffing
    add_header X-Content-Type-Options "nosniff" always;

    # XSS protection
    add_header X-XSS-Protection "1; mode=block" always;

    # Content Security Policy
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;

    # Referrer Policy
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Permissions Policy
    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

    # ========================================================================
    # Performance Optimizations
    # ========================================================================

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript
               application/json application/javascript application/xml+rss
               application/rss+xml application/atom+xml image/svg+xml;
    gzip_disable "msie6";

    # Client settings
    client_body_buffer_size 128k;
    client_max_body_size 20m;  # Increased for load balancer scenarios
    client_header_buffer_size 1k;
    large_client_header_buffers 4 16k;

    # Timeouts
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 75;  # Slightly higher for load balancer
    send_timeout 10;

    # ========================================================================
    # Logging with Backend Information
    # ========================================================================

    # Enhanced log format with upstream details
    log_format loadbalancer '$remote_addr - $remote_user [$time_local] "$request" '
                           '$status $body_bytes_sent "$http_referer" '
                           '"$http_user_agent" "$http_x_forwarded_for" '
                           'upstream_addr=$upstream_addr '
                           'upstream_status=$upstream_status '
                           'request_time=$request_time '
                           'upstream_response_time=$upstream_response_time '
                           'upstream_connect_time=$upstream_connect_time '
                           'upstream_header_time=$upstream_header_time';

    access_log /var/log/nginx/example.com.access.log loadbalancer;
    error_log /var/log/nginx/example.com.error.log warn;

    # ========================================================================
    # Load Balancer Proxy Configuration
    # ========================================================================

    location / {
        # Apply rate limiting
        limit_req zone=general burst=40 nodelay;
        limit_conn addr 20;

        # Proxy to upstream backend
        proxy_pass http://backend;

        # HTTP version for upstream
        proxy_http_version 1.1;

        # Essential proxy 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 header for keepalive
        proxy_set_header Connection "";

        # WebSocket support (if needed)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        # Proxy timeouts (tuned for load balancing)
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # Buffering settings
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 8k;
        proxy_busy_buffers_size 16k;

        # Error handling and failover
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        proxy_next_upstream_timeout 30s;

        # Disable caching for dynamic content
        proxy_cache_bypass $http_upgrade;
        proxy_no_cache $http_upgrade;

        # Redirect handling
        proxy_redirect off;
    }

    # ========================================================================
    # Admin/Management Endpoint (Optional)
    # ========================================================================

    # Restrict access to admin endpoints
    # location /admin/ {
    #     # IP whitelist
    #     allow 10.0.0.0/8;
    #     allow 192.168.0.0/16;
    #     deny all;
    #
    #     proxy_pass http://backend_admin;
    #     proxy_http_version 1.1;
    #     proxy_set_header Host $host;
    # }

    # ========================================================================
    # Health Check Endpoint
    # ========================================================================

    # Load balancer health check
    location /lb-health {
        access_log off;
        return 200 "Load Balancer: OK\n";
        add_header Content-Type text/plain;
    }

    # Proxy health check to backends
    location /backend-health {
        access_log off;
        proxy_pass http://backend/health;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_connect_timeout 5s;
        proxy_read_timeout 5s;
    }

    # ========================================================================
    # Static Content (Optional Caching)
    # ========================================================================

    # Cache static assets at load balancer level
    # location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf)$ {
    #     proxy_pass http://backend;
    #     proxy_cache static_cache;
    #     proxy_cache_valid 200 1d;
    #     proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    #     expires 1d;
    #     add_header Cache-Control "public";
    #     add_header X-Cache-Status $upstream_cache_status;
    # }
}

# ============================================================================
# WebSocket Connection Upgrade Map
# ============================================================================

# Place in http block of /etc/nginx/nginx.conf if WebSocket support is needed
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

# ============================================================================
# Deployment Instructions
# ============================================================================
# 1. Customize the following:
#    - server_name (lines 52, 70)
#    - ssl_certificate paths (lines 79-80)
#    - upstream backend servers (lines 22-24)
#    - Load balancing method (line 18)
#
# 2. Choose load balancing algorithm:
#    - round-robin: Default, distributes evenly
#    - least_conn: Routes to server with fewest connections (recommended)
#    - ip_hash: Session persistence based on client IP
#    - hash $request_uri: Route based on URL
#
# 3. Test configuration:
#    sudo nginx -t
#
# 4. Copy to sites-available:
#    sudo cp load-balancer.conf /etc/nginx/sites-available/example.com.conf
#
# 5. Create symbolic link:
#    sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/
#
# 6. Reload Nginx:
#    sudo systemctl reload nginx
#
# 7. Monitor backend health:
#    watch -n 2 'curl -s http://localhost/backend-health'
#
# ============================================================================
# Load Balancing Methods Comparison
# ============================================================================
# round-robin (default):
#   - Simple rotation through servers
#   - Good for: Evenly distributed load, stateless apps
#
# least_conn:
#   - Routes to server with fewest active connections
#   - Good for: Requests with varying processing times
#
# ip_hash:
#   - Same client always goes to same server (session persistence)
#   - Good for: Stateful applications, session management
#   - Note: Add 'ip_hash;' directive in upstream block
#
# hash $variable:
#   - Hash based on specified variable
#   - Good for: Cache optimization, custom routing logic
#   - Example: hash $request_uri consistent;
#
# ============================================================================
# Health Check Configuration
# ============================================================================
# Passive Health Checks (built-in):
#   - max_fails=3: Mark server down after 3 failed attempts
#   - fail_timeout=30s: Time to wait before retrying failed server
#
# Active Health Checks (Nginx Plus feature):
#   - For open-source Nginx, implement application-level health endpoints
#   - Monitor /backend-health endpoint externally
#
# ============================================================================
# Monitoring Tips
# ============================================================================
# 1. Check which backend served request:
#    tail -f /var/log/nginx/example.com.access.log | grep upstream_addr
#
# 2. Monitor backend response times:
#    tail -f /var/log/nginx/example.com.access.log | grep upstream_response_time
#
# 3. Check for backend failures:
#    grep "upstream" /var/log/nginx/error.log
#
# 4. Test load distribution:
#    for i in {1..100}; do curl -s https://example.com/ > /dev/null; done
#    # Then check access log for distribution
# ============================================================================
