http:
  routers:
    {{ domain.host | replace('.', '_') }}:
      rule: "Host(`{{ domain.host }}`)"
      entryPoints: [websecure]
      service: {{ domain.host | replace('.', '_') }}_svc
      {% set mids = [] %}
      {% if domain.security.basic_auth.enabled %}
      {% set _ = mids.append(domain.host | replace('.', '_') ~ "_auth") %}
      {% endif %}
      {% if domain.cors_passthrough %}
      {% set _ = mids.append(domain.host | replace('.', '_') ~ "_cors") %}
      {% endif %}
      {% if domain.security.rate_limit.enabled %}
      {% set _ = mids.append(domain.host | replace('.', '_') ~ "_ratelimit") %}
      {% endif %}
      {# Advanced headers: attach when HSTS enabled or extra headers present #}
      {% if domain.headers.hsts or (domain.headers.extra and domain.headers.extra|length > 0) %}
      {% set _ = mids.append(domain.host | replace('.', '_') ~ "_headers") %}
      {% endif %}
      {% if mids %}
      middlewares: {{ mids }}
      {% endif %}
      tls: {}
  services:
    {{ domain.host | replace('.', '_') }}_svc:
      loadBalancer:
        servers:
          {% for u in domain.upstreams %}
          - url: "http://{{ u.target }}"
          {% endfor %}
        passHostHeader: true
        {% if domain.sticky_cookie %}
        sticky:
          cookie:
            name: "{{ domain.sticky_cookie }}"
        {% endif %}
  middlewares:
    {% if domain.security.basic_auth.enabled %}
    {{ domain.host | replace('.', '_') }}_auth:
      basicAuth:
        usersFile: "/etc/traefik/htpasswd/{{ domain.host }}.htpasswd"
    {% endif %}
    {% if domain.cors_passthrough %}
    {{ domain.host | replace('.', '_') }}_cors:
      headers:
        accessControlAllowOriginList: ["*"]
        accessControlAllowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
        accessControlAllowHeaders: ["Authorization", "Content-Type", "X-Requested-With"]
        addVaryHeader: true
        accessControlMaxAge: 86400
    {% endif %}
    {% if domain.security.rate_limit.enabled %}
    {{ domain.host | replace('.', '_') }}_ratelimit:
      rateLimit:
        average: {{ (domain.security.rate_limit.requests_per_minute // 60) if (domain.security.rate_limit.requests_per_minute // 60) > 0 else 1 }}
        burst: {{ (domain.security.rate_limit.requests_per_minute // 10) if (domain.security.rate_limit.requests_per_minute // 10) > 0 else 1 }}
    {% endif %}
    {% if domain.headers.hsts or (domain.headers.extra and domain.headers.extra|length > 0) %}
    {{ domain.host | replace('.', '_') }}_headers:
      headers:
        {% if domain.headers.extra and domain.headers.extra|length > 0 %}
        customResponseHeaders:
          {% for k, v in domain.headers.extra.items() %}
          {{ k }}: {{ v | tojson }}
          {% endfor %}
        {% endif %}
        {% if domain.headers.hsts %}
        stsSeconds: 15768000
        stsIncludeSubdomains: true
        stsPreload: true
        {% endif %}
    {% endif %}
