#
# Nginx proxy for Elasticsearch + Kibana
#
# In this example we are restricting the access to the entire application using
# basic auth and filtered aliases based on the $remote_user.
#
# If you use this, you'll want to point config.js at http://FQDN:80/ instead of
# http://FQDN:9200
#
server {

  listen                *:80;
  server_name           localhost;


  # Apply basic auth to the entire application
  auth_basic "Restricted";
  auth_basic_user_file users.htpasswd;

  location / {
    root  /usr/share/kibana;
    index  index.html  index.htm;
  }

  location ~ ^/_aliases$ {
    proxy_pass http://127.0.0.1:9200;
    proxy_read_timeout 90;
  }

  location ~ ^/.*/_aliases$ {
    proxy_pass http://127.0.0.1:9200;
    proxy_read_timeout 90;
  }

  location ~ ^/_nodes$ {
    proxy_pass http://127.0.0.1:9200;
    proxy_read_timeout 90;
  }

  location ~ ^/.*/_mapping/field/\*$ {
    proxy_pass http://127.0.0.1:9200;
    proxy_read_timeout 90;
  }

  # Recursively change Logstash prefixed index names to user prefixed aliases.
  # This will process until the logstash prefix disappears
  location ~ ^/([^\*]*)logstash-(?<date>\d+.\d+.\d+)(,?[^\*/]+)*/_search$ {
    set $part1 $1;
    set $part3 $3;
    rewrite ^.*$ /${part1}${remote_user}-${date}${part3}/_search last; 
  }


  # All request to kibana-int also need to be proxied to an unique index per user.
  location ~ ^/kibana-int/(.*)$ {
    set $part1 $1;
    proxy_pass http://127.0.0.1:9200/kibana-int-${remote_user}/${part1};
    proxy_read_timeout 90;
  }

  location ~ ^/[^\*/]+/_search$ {
    proxy_pass http://127.0.0.1:9200;
    proxy_read_timeout 90;
  }


  # location ~ ^/kibana-int/dashboard/.*$ {
  #   proxy_pass http://127.0.0.1:9200;
  #   proxy_read_timeout 90;
  #   limit_except GET {
  #     proxy_pass http://127.0.0.1:9200;
  #     auth_basic "Restricted";
  #     auth_basic_user_file users.htpasswd;
  #   }
  # }

  # location ~ ^/kibana-int/temp.*$ {
  #   proxy_pass http://127.0.0.1:9200;
  #   proxy_read_timeout 90;
  #   limit_except GET {
  #     proxy_pass http://127.0.0.1:9200;
  #     auth_basic "Restricted";
  #     auth_basic_user_file users.htpasswd;
  #   }
  # }
}
