diff --git a/nginx.tmpl b/nginx.tmpl index 3aa28f4..b14e685 100644 --- a/nginx.tmpl +++ b/nginx.tmpl @@ -35,10 +35,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 }} @@ -65,6 +64,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 first cert name defined by containers w/ the same vhost */}} {{ $certName := (first (groupByKeys $containers "Env.CERT_NAME")) }} @@ -102,18 +115,38 @@ server { add_header Strict-Transport-Security "max-age=31536000; includeSubdomains"; + {{ if eq $pathCount 0 }} location / { proxy_pass http://{{ $host }}; } + {{ else }} + {{ range $path, $containers := $paths }} + {{ $sum := sha1 $path }} + {{ $suffix := printf "-%s" $sum }} + location {{ $path }} { + proxy_pass http://{{ $host }}{{ $suffix }}; + } + {{ end }} + {{ end }} } {{ else }} server { server_name {{ $host }}; + {{ if eq $pathCount 0 }} location / { proxy_pass http://{{ $host }}; } + {{ else }} + {{ range $path, $containers := $paths }} + {{ $sum := sha1 $path }} + {{ $suffix := printf "-%s" $sum }} + location {{ $path }} { + proxy_pass http://{{ $host }}{{ $suffix }}; + } + {{ end }} + {{ end }} } server {