Monitoring and Logging for Reverse Proxies

Monitoring and Logging for Reverse Proxies

Implement comprehensive monitoring:

#!/usr/bin/env python3
# /usr/local/bin/proxy-monitor.py

import requests
import json
import time
from datetime import datetime
import statistics

class ProxyMonitor:
    def __init__(self):
        self.backends = [
            'http://backend1.internal:8080',
            'http://backend2.internal:8080',
            'http://backend3.internal:8080'
        ]
        self.proxy_url = 'https://example.com'
        self.metrics = {
            'response_times': [],
            'error_count': 0,
            'backend_status': {}
        }
    
    def check_backend_health(self):
        """Check health of each backend server"""
        for backend in self.backends:
            try:
                response = requests.get(f"{backend}/health", timeout=5)
                self.metrics['backend_status'][backend] = {
                    'status': 'healthy' if response.status_code == 200 else 'unhealthy',
                    'response_time': response.elapsed.total_seconds(),
                    'status_code': response.status_code
                }
            except Exception as e:
                self.metrics['backend_status'][backend] = {
                    'status': 'down',
                    'error': str(e)
                }
    
    def test_proxy_performance(self):
        """Test reverse proxy performance"""
        test_endpoints = [
            '/',
            '/api/health',
            '/static/test.css'
        ]
        
        for endpoint in test_endpoints:
            try:
                start_time = time.time()
                response = requests.get(f"{self.proxy_url}{endpoint}", 
                                      headers={'User-Agent': 'ProxyMonitor/1.0'},
                                      timeout=10)
                response_time = time.time() - start_time
                
                self.metrics['response_times'].append({
                    'endpoint': endpoint,
                    'time': response_time,
                    'status_code': response.status_code,
                    'timestamp': datetime.now().isoformat()
                })
                
                if response.status_code >= 500:
                    self.metrics['error_count'] += 1
                    
            except Exception as e:
                self.metrics['error_count'] += 1
                print(f"Error testing {endpoint}: {e}")
    
    def analyze_metrics(self):
        """Analyze collected metrics"""
        if self.metrics['response_times']:
            response_times = [m['time'] for m in self.metrics['response_times']]
            
            analysis = {
                'avg_response_time': statistics.mean(response_times),
                'median_response_time': statistics.median(response_times),
                'max_response_time': max(response_times),
                'min_response_time': min(response_times),
                'error_rate': self.metrics['error_count'] / len(self.metrics['response_times']),
                'backend_health': self.metrics['backend_status']
            }
            
            # Alert on issues
            if analysis['avg_response_time'] > 1.0:
                self.send_alert("High average response time detected")
            
            if analysis['error_rate'] > 0.05:
                self.send_alert("High error rate detected")
            
            # Check backend health
            unhealthy_backends = [b for b, status in self.metrics['backend_status'].items() 
                                if status.get('status') != 'healthy']
            if unhealthy_backends:
                self.send_alert(f"Unhealthy backends: {', '.join(unhealthy_backends)}")
            
            return analysis
    
    def send_alert(self, message):
        """Send alert for critical issues"""
        print(f"ALERT: {message}")
        # Implement email/SMS/Slack notification here

if __name__ == '__main__':
    monitor = ProxyMonitor()
    monitor.check_backend_health()
    monitor.test_proxy_performance()
    analysis = monitor.analyze_metrics()
    
    print(json.dumps(analysis, indent=2))

Load balancing and reverse proxy configurations provide powerful security and performance benefits when properly implemented. Regular monitoring and maintenance ensure these benefits are realized while maintaining system reliability. The next chapter will explore common web server vulnerabilities and their prevention strategies.## Common Web Server Vulnerabilities and Prevention

Understanding and preventing common web server vulnerabilities is crucial for maintaining a secure online presence. This chapter provides an in-depth exploration of the most prevalent security vulnerabilities affecting Apache and Nginx servers, along with practical prevention strategies and remediation techniques. We'll examine real-world attack scenarios, demonstrate exploitation methods for educational purposes, and most importantly, show how to protect your servers against these threats.