# ============================================================================
# Nginx Reverse Proxy Configuration
# Generated for modern applications (Node.js, Python, Java, etc.)
# Standards: 2025 Security Best Practices
# ============================================================================

# 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=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

# 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 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 (adjust based on your needs)
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self';" always;

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

    # Permissions Policy (restrict browser features)
    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
               text/x-component text/x-cross-domain-policy;
    gzip_disable "msie6";

    # Client request settings
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 16k;

    # Timeouts
    client_body_timeout 12;
    client_header_timeout 12;
    keepalive_timeout 65;
    send_timeout 10;

    # ========================================================================
    # Logging
    # ========================================================================

    # Access log with timing information
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';

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

    # ========================================================================
    # Reverse Proxy Configuration
    # ========================================================================

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

        # Proxy to backend application - CUSTOMIZE THIS
        proxy_pass http://localhost:3000;

        # 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;

        # WebSocket support (required for real-time apps)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Proxy timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

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

        # Disable caching for dynamic content (enable if needed)
        proxy_cache_bypass $http_upgrade;
        proxy_no_cache $http_upgrade;

        # Error handling
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
        proxy_next_upstream_tries 3;

        # Redirect handling
        proxy_redirect off;
    }

    # ========================================================================
    # Static Files (Optional)
    # ========================================================================

    # Serve static files directly if your app has a public directory
    # Uncomment and customize as needed
    # location /static/ {
    #     alias /var/www/example.com/static/;
    #     expires 1y;
    #     add_header Cache-Control "public, immutable";
    #     access_log off;
    # }

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

    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    # ========================================================================
    # Error Pages
    # ========================================================================

    # Custom error pages (create these files)
    # error_page 404 /404.html;
    # error_page 500 502 503 504 /50x.html;

    # location = /50x.html {
    #     root /usr/share/nginx/html;
    # }
}

# ============================================================================
# Deployment Instructions
# ============================================================================
# 1. Customize the following:
#    - server_name (line 22, 30)
#    - ssl_certificate paths (lines 38-39)
#    - proxy_pass backend URL (line 130)
#    - client_max_body_size if needed (line 90)
#
# 2. Test configuration:
#    sudo nginx -t
#
# 3. Copy to sites-available:
#    sudo cp reverse-proxy.conf /etc/nginx/sites-available/example.com.conf
#
# 4. Create symbolic link:
#    sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/
#
# 5. Reload Nginx:
#    sudo systemctl reload nginx
#
# 6. Verify:
#    curl -I https://example.com
#
# ============================================================================
# Notes
# ============================================================================
# - This configuration assumes your backend is running on localhost:3000
# - WebSocket support is enabled by default
# - Rate limiting: 10 requests/second with burst of 20
# - Max request body size: 10MB (adjust client_max_body_size if needed)
# - All HTTP traffic is redirected to HTTPS
# - Security headers follow 2025 best practices
#
# For Let's Encrypt SSL certificates:
#   sudo certbot --nginx -d example.com -d www.example.com
# ============================================================================
