diff --git a/nginx.tmpl b/nginx.tmpl index 446ec31fc..127f19e32 100644 --- a/nginx.tmpl +++ b/nginx.tmpl @@ -37,10 +37,9 @@ server { return 503; } -{{ range $host, $containers := groupByMulti $ "Env.VIRTUAL_HOST" "," }} - -upstream {{ $host }} { -{{ range $container := $containers }} +{{ define "upstream" }} +upstream {{ .Host }}{{ .Suffix }} { +{{ range $container := .Containers }} {{ $addrLen := len $container.Addresses }} {{/* If only 1 port exposed, use that */}} {{ if eq $addrLen 1 }} @@ -67,6 +66,20 @@ upstream {{ $host }} { {{ end }} {{ end }} } +{{ end }} + +{{ range $host, $containers := groupByMulti $ "Env.VIRTUAL_HOST" "," }} +{{ $paths := groupBy $containers "Env.VIRTUAL_PATH" }} +{{ $pathCount := len $paths }} +{{ if eq $pathCount 0 }} + {{ template "upstream" dict "Host" $host "Suffix" "" "Containers" $containers }} +{{ else }} + {{ range $path, $containers := $paths }} + {{ $sum := sha1 $path }} + {{ $suffix := printf "-%s" $sum }} + {{ template "upstream" dict "Host" $host "Suffix" $suffix "Containers" $containers }} + {{ end }} +{{ end }} {{/* Get the VIRTUAL_PROTO defined by containers w/ the same vhost, falling back to "http" */}} {{ $proto := or (first (groupByKeys $containers "Env.VIRTUAL_PROTO")) "http" }} @@ -111,6 +124,7 @@ server { include {{ printf "/etc/nginx/vhost.d/%s" $host }}; {{ end }} + {{ if eq $pathCount 0 }} location / { proxy_pass {{ $proto }}://{{ $host }}; {{ if (exists (printf "/etc/nginx/htpasswd/%s" $host)) }} @@ -118,6 +132,19 @@ server { auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" $host) }}; {{ end }} } + {{ else }} + {{ range $path, $containers := $paths }} + {{ $sum := sha1 $path }} + {{ $suffix := printf "-%s" $sum }} + location {{ $path }} { + proxy_pass http://{{ $host }}{{ $suffix }}; + {{ if (exists (printf "/etc/nginx/htpasswd/%s" $host)) }} + auth_basic "Restricted {{ $host }}"; + auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" $host) }}; + {{ end }} + } + {{ end }} + {{ end }} } {{ else }} @@ -128,6 +155,7 @@ server { include {{ printf "/etc/nginx/vhost.d/%s" $host }}; {{ end }} + {{ if eq $pathCount 0 }} location / { proxy_pass {{ $proto }}://{{ $host }}; {{ if (exists (printf "/etc/nginx/htpasswd/%s" $host)) }} @@ -135,6 +163,19 @@ server { auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" $host) }}; {{ end }} } + {{ else }} + {{ range $path, $containers := $paths }} + {{ $sum := sha1 $path }} + {{ $suffix := printf "-%s" $sum }} + location {{ $path }} { + proxy_pass http://{{ $host }}{{ $suffix }}/; + {{ if (exists (printf "/etc/nginx/htpasswd/%s" $host)) }} + auth_basic "Restricted {{ $host }}"; + auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" $host) }}; + {{ end }} + } + {{ end }} + {{ end }} } {{ if (and (exists "/etc/nginx/certs/default.crt") (exists "/etc/nginx/certs/default.key")) }}