 server {

    set $app_home <%= node['nginx']['socketproxy']['root'] %>;

    <% if node['nginx']['sts_max_age'] -%>
    add_header Strict-Transport-Security "max-age=<%= node['nginx']['sts_max_age'] %>";
    <% end -%>

    listen <%= node['nginx']['port'] %> default;

    access_log <%= node['nginx']['log_dir'] %>/<%= node['nginx']['socketproxy']['logname'] %>.access.log<% if node['nginx']['access_log_options'] %> <%= node['nginx']['access_log_options'] %><% end %>;
    error_log <%= node['nginx']['log_dir'] %>/<%= node['nginx']['socketproxy']['logname'] %>.error.log <%= node['nginx']['socketproxy']['log_level'] %>;

    <% if node['nginx']['server_name'] -%>
    server_name ~^<%= node['nginx']['server_name'] %>\..*$;
    <% end -%>

    client_max_body_size 4G;
    keepalive_timeout 5;

    root $app_home/<%= node['nginx']['socketproxy']['default_app'] %>/<%= node['nginx']['socketproxy']['apps'][node['nginx']['socketproxy']['default_app']]['subdir'] %>/public;

    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;

    if ($request_method !~ ^(GET|HEAD|PUT|POST|DELETE|OPTIONS|PATCH)$ ) {
      return 405;
    }

    <% node['nginx']['socketproxy']['apps'].each do |app, app_conf|
      if app_conf['context_name']
        base_loc = "/#{app_conf['context_name'].gsub(/^\/+/,'').gsub(/\/+$/,'')}"
      else
        base_loc = ""
      end
    -%>

    location ~ "^<%= base_loc %>/assets/(.*/)*.*-[0-9a-f]{32}.*" {
      gzip_static on;
      expires     max;
      add_header  Cache-Control public;
    }

    location ^~ /<%= app_conf['context_name'] %> {

      alias $app_home/<%= app %>/<%= app_conf['subdir'] %>/public/;

      try_files $uri/index.html $uri.html $uri @app_<%= app %>;
      error_page 404              /404.html;
      error_page 422              /422.html;
      error_page 500 502 503 504  /500.html;
      error_page 403              /403.html;

    }

    location @app_<%= app %> {

      proxy_read_timeout 600;
      <%
        if app_conf['socket']['type']
          case app_conf['socket']['type']
          when 'unix'
      -%>
      proxy_pass http://unix:$app_home/<%= app %>/<%= app_conf['socket']['path'] %><% if app_conf['prepend_slash'] %>:/<% end %>;
      <%
          when 'tcp'
      -%>
      proxy_pass http://localhost:<%= app_conf['socket']['port'] -%>;
      <%
          end
        else
      -%>
      proxy_pass http://unix:$app_home/<%= app %>/<%= app_conf['socket_path'] %><% if app_conf['prepend_slash'] %>:/<% end %>;
      <%
        end
      -%>

    }

    <% end # node['nginx']['socketproxy']['apps'].each -%>

    error_page 500 502 504 /50x.html;
    location = /50x.html {
      root html;
    }

}
