worker_processes  auto;

events {
    worker_connections  64;
}

# this must be consistent with daemondo's --pidfile specification
pid /opt/local/var/run/nginx/nginx-adblock2privoxy.pid;

# error_log /opt/local/var/log/nginx/error_adblock2privoxy.log warn;
error_log off;

http {
  # access_log /opt/local/var/log/nginx/access_adblock2privoxy.log;
  access_log off;

  # avoid error 413 Request Entity Too Large
  # client_max_body_size 64M;
  keepalive_timeout 65;

  server {
    listen 127.0.0.1:8119;
    #ab2p css domain name (optional, should be equal to --domainCSS parameter)
    server_name localhost;

    ssl on;
    ssl_certificate      /opt/local/etc/adblock2privoxy/certs/adblock2privoxy-nginx.chain.pem;
    ssl_certificate_key  /opt/local/etc/adblock2privoxy/certs/adblock2privoxy-nginx.key.pem.decrypted;
    # use modern crypto
    # https://ssl-config.mozilla.org
    ssl_protocols TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /opt/local/etc/adblock2privoxy/certs/dhparam.pem;
    ssl_ciphers TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:EECDH+AESGCM:EDH+AESGCM;
    ssl_ecdh_curve secp384r1;
    ssl_session_timeout  180m;
    ssl_session_cache    shared:SSL:20m;
    ssl_session_tickets  off;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";

    # comply with Content Security policy
    add_header Content-Type "text/css";
    add_header X-Content-Type-Options nosniff;

    #root = --webDir parameter value
    root /opt/local/etc/adblock2privoxy/css;

    # If useHTTP is set:
    # Ensure that http://localhost:8119/ is a legitimate (200 return code)
    # default page; use as iOS proxy.pac blackhole
    # Test with curl -I --proxy http://127.0.0.1:8119 http://www.foo.com/bar?q=snafoo
    location / {
      return 301 http://$server_name:$server_port/@blackhole?;
      # rewrite ^ /default.html break;
    }

    location ~ ^/@blackhole {
      default_type text/html;
      return 200 "<!DOCTYPE html>\n<html>\n<head>\n<meta charset='utf-8'>\n</head>\n<body>\n<p><a href=\"https://github.com/essandess/adblock2privoxy\">adblock2privoxy</a> blackhole 🕳</p>\n</body>\n</html>\n";
    }

    location ~ ^/+(ab2p(?:\.common)?\.css) {
        # ab2p.css in top-level directory
        try_files $uri $1;
    }

    location ~ ^/[^/.]+\..+/ab2p\.css$ {
        # first reverse domain names order
    rewrite ^/([^/]*?)\.([^/.]+)(?:\.([^/.]+))?(?:\.([^/.]+))?(?:\.([^/.]+))?(?:\.([^/.]+))?(?:\.([^/.]+))?(?:\.([^/.]+))?(?:\.([^/.]+))?/ab2p.css$ /$9/$8/$7/$6/$5/$4/$3/$2/$1/ab2p.css last;
    }

    location ~ (^.*/+)[^/]+/+ab2p\.css {
        # then try to get CSS for current domain
        # if it is unavailable - get CSS for parent domain
        try_files $uri $1ab2p.css;
    }
  }
}
