#
# {{ ansible_managed }}
#


{% if nginx_default_sites is defined and "credentials" in nginx_default_sites %}
  {% set default_site = "default_server" %}
{% else %}
  {% set default_site = "" %}
{% endif %}

upstream credentials_app_server {
{% for host in NGINX_CREDENTIALS_GUNICORN_HOSTS %}
    server {{ host }}:{{ credentials_gunicorn_port }} fail_timeout=0;
{% endfor %}
}

# The Origin request header indicates where a fetch originates from. It doesn't include any path information,
# but only the server name (e.g. https://www.example.com).
# See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin for details.
#
# Here we set the value that is included in the Access-Control-Allow-Origin response header. If the origin is one
# of our known hosts--served via HTTP or HTTPS--we allow for CORS. Otherwise, we set the "null" value, disallowing CORS.
map $http_origin $cors_origin {
  default "null";
{% for host in CREDENTIALS_CORS_ORIGIN_WHITELIST %}
  "~*^https?:\/\/{{ host|replace('.', '\.') }}$" $http_origin;
{% endfor %}
}

server {
  server_name {{ CREDENTIALS_HOSTNAME }};

  {% if NGINX_ENABLE_SSL %}

  listen {{ CREDENTIALS_NGINX_PORT }} {{ default_site }};
  listen {{ CREDENTIALS_SSL_NGINX_PORT }} ssl;

  ssl_certificate /etc/ssl/certs/{{ NGINX_SSL_CERTIFICATE|basename }};
  ssl_certificate_key /etc/ssl/private/{{ NGINX_SSL_KEY|basename }};
  # request the browser to use SSL for all connections
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

  {% else %}
  listen {{ CREDENTIALS_NGINX_PORT }} {{ default_site }};
  {% endif %}

  location ~ ^{{ CREDENTIALS_MEDIA_URL }}(?P<file>.*) {
    root {{ CREDENTIALS_MEDIA_ROOT }};
    try_files /$file =404;
  }

  location ~ ^{{ CREDENTIALS_STATIC_URL }}(?P<file>.*) {
    root {{ CREDENTIALS_STATIC_ROOT }};
    add_header Cache-Control "max-age=31536000";
    add_header 'Access-Control-Allow-Origin' $cors_origin;

    # Inform downstream caches to take certain headers into account when reading/writing to cache.
    add_header 'Vary' 'Accept-Encoding,Origin';

    try_files /$file =404;
  }

  location / {
    try_files $uri @proxy_to_app;
  }

  {% if NGINX_ROBOT_RULES|length > 0 %}
  location /robots.txt {
      root {{ nginx_app_dir }};
      try_files $uri /robots.txt =404;
  }
  {% endif %}

  location @proxy_to_app {
    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header X-Forwarded-Port $http_x_forwarded_port;
    proxy_set_header X-Forwarded-For $http_x_forwarded_for;
    proxy_set_header Host $http_host;

    proxy_redirect off;
    proxy_pass http://credentials_app_server;
  }

  # Forward to HTTPS if we're an HTTP request...
  if ($http_x_forwarded_proto = "http") {
    set $do_redirect "true";
  }

  # Run our actual redirect...
  if ($do_redirect = "true") {
    rewrite ^ https://$host$request_uri? permanent;
  }
}
