user www-data;
worker_processes {{ nginx_worker_processes }};
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections {{ nginx_worker_connections }};
    use epoll;
    multi_accept on;
}

http {
    ##
    # Basic Settings
    ##
    sendfile {{ tcp_optimizations.sendfile }};
    tcp_nopush {{ tcp_optimizations.tcp_nopush }};
    tcp_nodelay {{ tcp_optimizations.tcp_nodelay }};
    keepalive_timeout {{ nginx_keepalive_timeout }};
    types_hash_max_size 2048;
    server_tokens off;
    
    server_names_hash_bucket_size 64;
    
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # DSGVO-konforme Logging
    ##
    map $remote_addr $anonymized_ip {
        ~(?P<ip>\d+\.\d+\.\d+)\.\d+ $ip.0;
        ~(?P<ipv6>[^:]+:[^:]+:[^:]+:[^:]+):.* $ipv6::;
        default 0.0.0.0;
    }
    
    log_format cdn_format '$anonymized_ip - $remote_user [$time_local] '
                         '"$request" $status $body_bytes_sent '
                         '"$http_referer" "$http_user_agent" '
                         'rt=$request_time '
                         'cache="$upstream_cache_status" '
                         'cdn_node="{{ inventory_hostname }}"';
    
    access_log /var/log/nginx/access.log cdn_format;
    error_log /var/log/nginx/error.log warn;

    ##
    # Cache Paths
    ##
    proxy_cache_path /var/cache/nginx/static levels=1:2 keys_zone=static_cache:100m 
                     max_size={{ cache_size }} inactive=7d use_temp_path=off;
    proxy_cache_path /var/cache/nginx/images levels=1:2 keys_zone=images_cache:100m 
                     max_size={{ cache_size }} inactive=30d use_temp_path=off;
    proxy_cache_path /var/cache/nginx/html levels=1:2 keys_zone=html_cache:50m 
                     max_size=5g inactive=1h use_temp_path=off;

    ##
    # Upstream zu Origin-Servern
    ##
    upstream origin_servers {
{% for host in groups['origin_servers'] %}
        server {{ hostvars[host]['ansible_default_ipv4']['address'] }}:443 
               weight=1 max_fails=3 fail_timeout=30s;
{% endfor %}
        keepalive 32;
        keepalive_requests 1000;
        keepalive_timeout 60s;
    }

    ##
    # Include configurations
    ##
    include /etc/nginx/includes/*.conf;
    include /etc/nginx/sites-enabled/*;
}
