# Nginx Rate Limiting Configuration for SellZaki
# Add this to your nginx http block (usually in /etc/nginx/nginx.conf)

# Define rate limit zones
# Zone 1: General API rate limiting (10 requests/second per IP)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

# Zone 2: Aggressive rate limiting for search endpoints (2 requests/second per IP)
limit_req_zone $binary_remote_addr zone=search_limit:10m rate=2r/s;

# Zone 3: Login rate limiting (5 requests per minute per IP)
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;

# Zone 4: Connection limiting (max 10 concurrent connections per IP)
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

# Add this to your server block for SellZaki

server {
    # ... your existing server config ...

    # Connection limit: max 10 concurrent connections per IP
    limit_conn conn_limit 10;

    # General API rate limiting
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        limit_req_status 429;
        
        # Pass to PHP-FPM
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Aggressive rate limiting for search endpoints
    location ~ ^/api/.*/search {
        limit_req zone=search_limit burst=5 nodelay;
        limit_req_status 429;
        
        # Log blocked requests
        access_log /var/log/nginx/search-rate-limit.log combined;
        
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Login endpoint rate limiting
    location ~ ^/api/auth/login$ {
        limit_req zone=login_limit burst=3 nodelay;
        limit_req_status 429;
        
        # Log blocked login attempts
        access_log /var/log/nginx/login-rate-limit.log combined;
        
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Block known bad user agents
    if ($http_user_agent ~* (bot|crawler|spider|scraper|curl|wget|python-requests)) {
        return 403;
    }

    # Block requests with no user agent
    if ($http_user_agent = "") {
        return 403;
    }

    # ... rest of your server config ...
}

# Optional: Create a blacklist file for manually blocking IPs
# Create file: /etc/nginx/conf.d/blocked-ips.conf
# Add IPs like this:
# deny 41.44.117.225;
# deny 192.168.1.100;
# allow all;
#
# Then include it in your server block:
# include /etc/nginx/conf.d/blocked-ips.conf;
