Skip to content

Commit 0fd9535

Browse files
Fokirclaude
andcommitted
fix(nginx): use real client scheme for auth redirect behind proxy
Behind a TLS-terminating proxy (e.g. Cloudflare) the origin connection may be plain HTTP, so $scheme is http and the login redirect points to http://, which the proxy upgrades back to https, causing a redirect loop. Derive $real_scheme from X-Forwarded-Proto when present and fall back to $scheme for direct connections, then use it in the login redirect and the upstream X-Forwarded-Proto header. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 974524d commit 0fd9535

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

internal/nginx/template.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ import (
77

88
// locationBlock is a reusable sub-template for proxy location directives.
99
const locationBlock = `
10+
# Determine the real client-facing scheme. When behind a proxy that
11+
# terminates TLS (e.g. Cloudflare), the origin connection may be plain
12+
# HTTP, so $scheme is unreliable. Trust X-Forwarded-Proto when present;
13+
# for direct connections the header is absent and we fall back to $scheme.
14+
set $real_scheme $scheme;
15+
if ($http_x_forwarded_proto = "https") {
16+
set $real_scheme "https";
17+
}
1018
{{- if .HasAuth}}
1119
# Cookie-based auth via system-control
1220
location = /_sc_auth_verify {
@@ -39,7 +47,7 @@ const locationBlock = `
3947
proxy_set_header Host $host;
4048
proxy_set_header X-Real-IP $remote_addr;
4149
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
42-
proxy_set_header X-Forwarded-Proto $scheme;
50+
proxy_set_header X-Forwarded-Proto $real_scheme;
4351
proxy_http_version 1.1;
4452
proxy_set_header Upgrade $http_upgrade;
4553
proxy_set_header Connection "upgrade";
@@ -53,7 +61,7 @@ const locationBlock = `
5361
5462
{{- if .HasAuth}}
5563
location @login_redirect {
56-
return 302 $scheme://$host/_sc_auth/login?domain=$host&redirect=$scheme://$host$request_uri;
64+
return 302 $real_scheme://$host/_sc_auth/login?domain=$host&redirect=$real_scheme://$host$request_uri;
5765
}
5866
{{- end}}`
5967

0 commit comments

Comments
 (0)