server {
    listen 80;
    listen [::]:80;
    server_name {{ tracker_domain }};

    # Redirect to HTTPS if SSL is enabled
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name {{ tracker_domain }};
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/{{ tracker_domain }}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{{ tracker_domain }}/privkey.pem;
    
    # Proxy to tracker app
    location / {
        proxy_pass http://127.0.0.1:5000;
        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;
    }
    
    # Specific location for tracking pixel
    location ~ ^/pixel/(.+)\.png$ {
        proxy_pass http://127.0.0.1:5000/pixel/$1.png;
        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;
        
        # Cache control - don't cache tracking pixels
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        expires off;
    }
    
    # Security headers
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer" always;
    
    {% if zero_logs | default(true) %}
    # Disable logging for privacy
    access_log off;
    error_log /dev/null crit;
    {% endif %}
}