# nginx.conf — Stack nginx + varnish
# nginx : TLS frontend (port 443) + proxy vers Varnish (port 6081)
# Port 80 : redirige vers HTTPS

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
}

http {
    include      /etc/nginx/mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;
    keepalive_requests 200;

    log_format main '$remote_addr [$time_local] "$request" $status '
                    'ssl=$ssl_protocol via_varnish=$upstream_http_x_varnish';
    access_log /var/log/nginx/access.log main;

    # Backend Varnish (HTTP cleartext, pas de TLS)
    upstream varnish_backend {
        server 127.0.0.1:6081;
        keepalive 32;
    }

    # ── Port 80 ─────────────────────────────────────────────────────────────
    server {
        listen 80;
        server_name _;
        location /health {
            return 200 '{"status":"ok","stack":"nginx-varnish"}';
            add_header Content-Type application/json;
        }
        location / {
            return 301 https://$host$request_uri;
        }
    }

    # ── Port 443 (TLS frontend → proxy Varnish) ──────────────────────────────
    server {
        listen 443 ssl http2;
        server_name _;

        ssl_certificate     /etc/pki/tls/certs/nginx.crt;
        ssl_certificate_key /etc/pki/tls/private/nginx.key;
        ssl_protocols       TLSv1.2 TLSv1.3;
        ssl_ciphers         HIGH:!aNULL:!MD5;
        ssl_session_cache   shared:SSL:10m;

        # Transmission de l'IP réelle du client vers Varnish
        proxy_set_header X-Real-IP       $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host            $http_host;

        location /health {
            return 200 '{"status":"ok","stack":"nginx-varnish","tls":true}';
            add_header Content-Type application/json;
        }

        location / {
            proxy_pass         http://varnish_backend;
            proxy_http_version 1.1;
            # HTTP/2 terminé côté nginx ; nginx→Varnish est HTTP/1.1 cleartext
            proxy_set_header   Connection "";
        }
    }
}
