upstream analytics_api_app_server {
    {% for host in nginx_analytics_api_gunicorn_hosts %}
        server {{ host }}:{{ analytics_api_gunicorn_port }} fail_timeout=0;
    {% endfor %}
}

server {
  listen {{ ANALYTICS_API_NGINX_PORT }} default_server;

  # Nginx does not support nested condition or or conditions so
  # there is an unfortunate mix of conditonals here.
  {% if NGINX_REDIRECT_TO_HTTPS %}
     {% if NGINX_HTTPS_REDIRECT_STRATEGY == "scheme" %}
  # Redirect http to https over single instance
  if ($scheme != "https") 
  { 
   set $do_redirect_to_https "true";
  }
 
    {% elif NGINX_HTTPS_REDIRECT_STRATEGY == "forward_for_proto" %}

  # Forward to HTTPS if we're an HTTP request... and the server is behind ELB 
  if ($http_x_forwarded_proto = "http") 
  {
   set $do_redirect_to_https "true";
  }
     {% endif %}

  # Execute the actual redirect
  if ($do_redirect_to_https = "true")
  {
  return 301 https://$host$request_uri;
  }
  {% endif %}
  
  location ~ ^/static/(?P<file>.*) {
    root {{ COMMON_DATA_DIR }}/{{ analytics_api_service_name }};
    try_files /staticfiles/$file =404;
  }

  location / {
    try_files $uri @proxy_to_app;
  }

  {% include "robots.j2" %}

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://analytics_api_app_server;
  }
}

