{% if use_ssl and hostname %}
server {
    listen 80;
    server_name {{ hostname.split('.')[0] }};
    rewrite ^ https://{{hostname}}$request_uri? permanent;
}

server {
    listen 80 default_server;
    server_name {{hostname}};
    return 307 https://$host$request_uri;
}

{% endif %}

server {
    {% if hostname %}
    server_name {{ hostname }};
    {% endif %}

    ## regular http - disable for https
    listen 80;

    access_log /dev/stdout;

    gzip on;
    gzip_proxied any;
    gzip_types text/plain text/xml text/css application/x-javascript application/javascript;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log warn;

    {% if use_ssl %}
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ssl_certificate /conf/certificate.crt;
    ssl_certificate_key /conf/server.key;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;
    ssl_session_tickets off;

    {% endif %}


    {% for location in project.get_sorted_locations() %}

      {% if location.is_static() %}
          location ~ ^{{location.mountpoint.without_trailing_slash()}}/(.*)$ {

            root /;
            {% if location.is_frontend_app() %}
            try_files {{location.fs_paths[0]}} =404;
            {% else %}
            try_files {% for fs_path in location.fs_paths -%}
            {%- if os.path.isfile(fs_path) -%}
            {{fs_path}} {% else %} {{fs_path}}/$1 {{fs_path}}/$1/index.html
            {%- endif -%}
            {%- endfor %} =404;
            {% endif %}

            gzip_static on;
          }
      {% else %}
          location ~ ^{{location.mountpoint.without_trailing_slash()}}(/.*)?$ {
              proxy_set_header Host $http_host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto $scheme;
              proxy_pass http://wsgi:8000;
              client_max_body_size 10m;
          }
      {% endif %}
    {% endfor %}
}
