# LOCAL PATH {{ upstream_name }}: {{ upstream.domain }} -> {{ upstream.path }}

server {
    server_name  {{ upstream.domain }}{% if 'domains' in upstream and upstream.domains is sequence %}{% for domain in upstream.domains %} {{ domain }}{% endfor %}{% endif %};
{% if not (nginx_sslmode|default('enable') == 'enforce' or upstream.enforce_https is defined and upstream.enforce_https|bool) %}
    listen       {{ nginx_port|default(80) }};
{% endif %}
{% if nginx_sslmode|default('enable') != 'disable' %}
    listen       {{ nginx_ssl_port|default(443) }} ssl;
    ssl_certificate     {% if upstream.cert is defined %}{{ upstream.cert }}{% else %}/etc/nginx/conf.d/cert/{{ upstream.domain }}.crt{% endif %};
    ssl_certificate_key {% if upstream.key is defined %}{{ upstream.key }}{% else %}/etc/nginx/conf.d/cert/{{ upstream.domain }}.key{% endif %};
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
{% endif %}

{% if 'log' in upstream and upstream.log != '' %}
    access_log /var/log/nginx/{{ upstream.log }};
{% endif %}

{% if upstream.auth is defined and upstream.auth | bool %}
    auth_basic "{{ upstream.realm | default('Auth ' + upstream_name|string ) }}";
    auth_basic_user_file /etc/nginx/.htpasswd;
{% endif %}

{% if upstream.certbot is defined and upstream.certbot != '' %}
    location ^~ /.well-known/acme-challenge/ {
        root {{ nginx_home|default('/www') }}/acme;
        try_files $uri =404;
    }
{% endif %}

    # local path server
    location / {
        root        {{ upstream.path }};
        index       index.html;
{% if 'index' in upstream and upstream.index|bool %}
        autoindex   on;
        autoindex_exact_size on;
        autoindex_localtime on;
        autoindex_format html;
{% else %}
        autoindex   off;
{% endif %}
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        directio 1m;
        output_buffers 2 1m;
        aio threads;
    }

{% if upstream.config is defined and upstream.config != '' %}
{{ upstream.config }}
{% endif %}
}

{% if nginx_sslmode|default('enable') == 'enforce' or upstream.enforce_https is defined and upstream.enforce_https|bool %}
# redirect http to https
server {
    listen 80;
    server_name {{ upstream.domain }}{% if 'domains' in upstream and upstream.domains is sequence %}{% for domain in upstream.domains %} {{ domain }}{% endfor %}{% endif %};

{% if upstream.certbot is defined and upstream.certbot != '' %}
    location ^~ /.well-known/acme-challenge/ {
        auth_basic off;
        root {{ nginx_home|default('/www') }}/acme;
        try_files $uri =404;
    }

    location / {
        return 301 https://$host$request_uri;
    }
{% else %}
    return 301 https://$host$request_uri;
{% endif %}
}
{% endif %}