upstream php-handler {
    server {{ item.listen }};
    #server unix:/var/run/php5-fpm.sock;
}

server {
    listen 80;
    listen [::]:80;
    server_name {{ item.nginx_servername }};
    # enforce https
    location ~ /\.(?!well-known).* {
        deny all;
        access_log off;
        log_not_found off;
        return 404;
    }
    include /etc/nginx/snippets/letsencrypt-proxy.conf;
    location / {
        return 301 https://$server_name$request_uri;
    }
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name {{ item.nginx_servername }};

    include /etc/nginx/snippets/nginx-server-ssl.conf;
    server_tokens off;
    
    {% if haproxy_ips is defined %}
    # We are behind haproxy
    {% for ip in haproxy_ips %}
    set_real_ip_from {{ ip }};
    {% endfor %}
    real_ip_header X-Forwarded-For;
    {% endif %}

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    # add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    #
    # WARNING: Only add the preload option once you read about
    # the consequences in https://hstspreload.org/. This option
    # will add the domain to a hardcoded list that is shipped
    # in all major browsers and getting removed from this list
    # could take several months.
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

    # Path to the root of your installation
    root {{ item.doc_root }};

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }
    location /simplesaml {
        alias {{ simplesaml_install_dir }}/www;
        location ~ ^(?<prefix>/simplesaml)(?<phpfile>.+?\.php)(?<pathinfo>/.*)?$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass php-handler;
            fastcgi_split_path_info ^(.+?\.php)(/.+)$;
            fastcgi_param SCRIPT_FILENAME $document_root$phpfile;
            fastcgi_param PATH_INFO $pathinfo if_not_empty;
        }
    }
}