EthioDeploy
DocsPricingDomainsBlogToolsChangelog

Blog/Fix deploy errors

ERR_TOO_MANY_REDIRECTS behind a proxy: causes and fixes

BS
Brook SolomonPublished November 24, 2026
Share on XShare on LinkedIn
ERR_TOO_MANY_REDIRECTS

THE SHORT ANSWER

ERR_TOO_MANY_REDIRECTS behind a proxy almost always means your app thinks an HTTPS request is HTTP and redirects it to HTTPS, forever. The proxy ended TLS and forwarded plain HTTP with an X-Forwarded-Proto: https header the app ignores. Tell the framework to trust its proxy: app.set("trust proxy", 1) in Express, SECURE_PROXY_SSL_HEADER in Django, trustProxies in Laravel, config.assume_ssl in Rails, AUTH_TRUST_HOST for Auth.js. If Cloudflare sits in front with SSL set to Flexible, change it to Full (strict). The other common loop is two layers redirecting in opposite directions, such as www to apex in one and apex to www in the other.

Why does a proxy cause a redirect loop?

In most hosting setups, HTTPS ends at a proxy or load balancer. The proxy decrypts the request and forwards it to your app over plain HTTP on a private network, adding headers that describe the original request:

X-Forwarded-Proto: https
X-Forwarded-Host: app.example.com
X-Forwarded-For: 203.0.113.7

If the app doesn't read X-Forwarded-Proto, every request looks like HTTP. An app that forces HTTPS answers with a redirect to https://. The browser follows it, the proxy forwards it as HTTP again, and the app redirects again. The browser follows a limited number of redirects and then stops with ERR_TOO_MANY_REDIRECTS.

Frameworks don't trust X-Forwarded-* headers by default, because any client can send them. Trusting them is safe only when a proxy you control strips the client's copy and sets its own. So the fix is always one setting that says “my proxy is trustworthy”.

See the loop with curl. Each hop prints its status and the next location:

curl -sIL https://app.example.com/ | grep -iE '^(HTTP|location)'

The same URL repeating means the app or proxy can't see HTTPS. Two hosts swapping back and forth means two layers disagree about www.

Quick checklist

StackWhat forces HTTPSWhat makes it see the proxy
ExpressYour middleware checking req.secureapp.set("trust proxy", 1)
DjangoSECURE_SSL_REDIRECT = TrueSECURE_PROXY_SSL_HEADER
LaravelMiddleware checking $request->secure()trustProxies(at: '*') in bootstrap/app.php
Railsconfig.force_ssl = trueconfig.assume_ssl = true
Next.js with Auth.jsAuth middleware sending you to sign inAUTH_TRUST_HOST=true, and secureCookie on getToken
Cloudflare in frontThe origin redirects HTTP to HTTPSSSL/TLS mode Full (strict), not Flexible

How do you fix it in Express?

Turn on trust proxy. Express then fills req.protocol from X-Forwarded-Proto, and req.secure follows it:

const app = express();
app.set("trust proxy", 1); // one proxy in front of the app

app.use((req, res, next) => {
  if (req.secure) return next();
  res.redirect(301, `https://${req.headers.host}${req.originalUrl}`);
});

The value says which hops to trust. A number is how many proxies sit in front of the app. You can also pass addresses or the names loopback, linklocal and uniquelocal. Express warns that with true, the last trusted proxy has to overwrite X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, “otherwise it may be possible for the client to provide any value”.

The same setting fixes secure session cookies that never get set behind a proxy, which shows up as a login that loops back to the login page. NestJS on Express uses the same call on the app instance.

How do you fix it in Django?

Django's docs describe this exact loop under SECURE_SSL_REDIRECT: if turning it on “causes infinite redirects, it probably means your site is running behind a proxy and can't tell which requests are secure”. Tell Django which header the proxy sets:

# settings.py
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = True

Only set it when the proxy strips any X-Forwarded-Proto a client sends and sets its own. If it doesn't, a client could make plain HTTP look secure. The same fix clears CSRF 403s caused by the scheme mismatch; see Django DisallowedHost and CSRF errors behind a proxy.

How do you fix it in Laravel?

Laravel's docs describe the symptom as the app that “does not generate HTTPS links” behind a TLS-terminating load balancer. When your own middleware redirects whenever $request->secure() is false, that becomes a loop. Trust the proxy in bootstrap/app.php (Laravel 11 and later):

->withMiddleware(function (Middleware $middleware): void {
    $middleware->trustProxies(at: '*');
})

'*' trusts any proxy, which the docs suggest when you don't know the load balancer's addresses. List IPs or CIDR ranges instead if you do. Set APP_URL to your https:// address too. More on the related errors in Laravel 500 error after deploy.

How do you fix it in Rails?

config.force_ssl redirects HTTP to HTTPS, sets HSTS and marks cookies secure. config.assume_ssl “makes application believe that all requests are arriving over SSL”: its middleware sets HTTPS=on and X-Forwarded-Proto: https on every request before your app sees it. Behind a proxy that ends TLS, use both:

# config/environments/production.rb
config.assume_ssl = true
config.force_ssl = true

# Skip the redirect for the health check, as the Rails template suggests
config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } }

Rails 8 generates both lines commented out, and turns them on only for apps created with --skip-kamal. assume_ssl is only safe when every request really did arrive over HTTPS at the proxy.

What about Next.js with NextAuth or Auth.js?

Next.js itself doesn't force HTTPS, so a loop in a Next.js app usually comes from an auth check in proxy.ts (formerly middleware.ts) that keeps sending a signed-in user to the sign-in page, which sends them back. Three settings cause it:

  • Host not trusted. Auth.js v5 builds its URLs from the request. Its deployment docs say to set AUTH_TRUST_HOST=true “when deploying your application behind a reverse proxy”; it's inferred only on Vercel and Cloudflare Pages. With it, Auth.js reads X-Forwarded-Host and X-Forwarded-Proto.
  • Cookie name mismatch. On HTTPS, Auth.js names the session cookie __Secure-authjs.session-token. If you call getToken() yourself, it defaults to secureCookie: false and looks for authjs.session-token, finds nothing, and your check redirects to sign-in. Pass secureCookie: true in production. In next-auth v4 the default comes from NEXTAUTH_URL starting with https://.
  • Wrong canonical URL. In v4, NEXTAUTH_URL must be the canonical URL of the site. An http:// value in production also turns off secure cookies, so the cookie set and the cookie looked for disagree.
// proxy.ts
import { getToken } from "next-auth/jwt";
import { NextResponse, type NextRequest } from "next/server";

export async function proxy(req: NextRequest) {
  const token = await getToken({
    req,
    secret: process.env.AUTH_SECRET,
    secureCookie: process.env.NODE_ENV === "production",
  });
  if (!token) return NextResponse.redirect(new URL("/login", req.url));
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*"] };

Keep the sign-in page and /api/auth out of the matcher, or the redirect target is protected too.

Why does Cloudflare Flexible SSL loop?

In Flexible mode, Cloudflare serves HTTPS to visitors but “sends unencrypted requests to your origin server over HTTP”. If the origin redirects HTTP to HTTPS, which most hosts and frameworks do, the browser lands back on Cloudflare, which again calls the origin over HTTP. Cloudflare's own troubleshooting page names this loop and gives two fixes: remove the origin's redirect, or set the encryption mode to Full or higher. Choose Full (strict) when the origin has a valid certificate.

Cloudflare does send X-Forwarded-Proto with the scheme the visitor used, so an app that trusts it won't loop. A proxy that redirects on the connection itself, before the app runs, still will. The loop can also run the other way: with Full or Always Use HTTPS on, an origin that redirects HTTPS back to HTTP loops too.

Also check for two layers that disagree about www: a Cloudflare redirect rule from www to the bare domain plus an app or host rule from the bare domain to www sends visitors back and forth forever.

What happens on EthioDeploy?

HTTPS ends at Traefik. Port 80 only answers with a 301 to the same URL on https://; it never forwards to your app. Your app gets every request over plain HTTP with X-Forwarded-Proto: https and the original Host header. Traefik overwrites any X-Forwarded-* headers a client sends, and keeps them only from Cloudflare's published IP ranges. So trusting the header is safe, and the settings above are what to use:

  • Express and NestJS: app.set("trust proxy", 1).
  • Django: SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https").
  • Laravel: trustProxies(at: '*').
  • Rails: config.assume_ssl = true.
  • FastAPI and other Uvicorn apps: the env var FORWARDED_ALLOW_IPS=*.
  • Auth.js: AUTH_TRUST_HOST=true and AUTH_URL set to your https address.

You don't need an HTTP-to-HTTPS redirect in the app at all, because port 80 already does it. If you keep one, it never fires once the app trusts the header.

Custom domains: the custom domains guide asks for DNS only (grey cloud) records if your DNS is on Cloudflare. If you proxy the domain through your own Cloudflare account anyway, set SSL/TLS to Full (strict); our side has a valid certificate for the domain. Never use Flexible: it sends Cloudflare to port 80, which only redirects. With Cloudflare's X-Forwarded-Proto: https on that request, Traefik has nothing to redirect and, in our test with the same Traefik version and settings, answered 418 instead of reaching the app. If you turned on “Forward root to www”, don't also redirect www to the bare domain in your app or in Cloudflare.

Framework setup is in the Express, Django, Laravel and Rails deploy guides.

Questions

Usually the app forces HTTPS but can't see that the visitor used HTTPS, because the proxy ended TLS and forwarded plain HTTP. The app redirects every request to HTTPS, forever. Make the framework trust the proxy's X-Forwarded-Proto header.

Set SSL/TLS encryption mode to Full (strict) instead of Flexible. Flexible connects to your server over HTTP, and a server that redirects HTTP to HTTPS sends the browser back to Cloudflare in a loop. Also make sure Cloudflare and your server don't redirect www and the bare domain in opposite directions.

Only when a proxy you control strips the header from client requests and sets its own. Otherwise any client can claim HTTPS. Express, Django, Laravel and Rails all leave it untrusted by default for this reason.

Often the session cookie is named __Secure-authjs.session-token on HTTPS, while a getToken() call without secureCookie: true looks for authjs.session-token and finds nothing. Set secureCookie in production, set AUTH_TRUST_HOST=true behind a proxy, and keep the login page out of the protected matcher.

Fix the server first, then clear the site's cookies and test in a private window, or run curl -sIL on the URL to see exactly what the server sends now, hop by hop.

Sources

Checked on November 24, 2026:

  • Cloudflare: ERR_TOO_MANY_REDIRECTS
  • Cloudflare: HTTP headers
  • Express: Express behind proxies
  • Express 5: req.secure
  • Django 5.2: SECURE_PROXY_SSL_HEADER
  • Laravel 13: Configuring trusted proxies
  • Rails: Configuring Rails applications
  • Rails source: AssumeSSL middleware
  • Auth.js: Deployment
  • Auth.js source: getToken
  • NextAuth.js v4: Options
  • Traefik: EntryPoints

Push a repo. Get a URL.

  • Custom domains
  • Deploy an Express app
  • Deploy a Django app
  • Deploy a Laravel app
  • Deploy a Rails app
Start free

Join the EthioDeploy Telegram

Release notes as they ship, plus deploy help from the team and other developers.

Join on Telegram
BS
WRITTEN BYBrook SolomonFounder, EthioDeploy

Brook Solomon founded EthioDeploy and builds its deploy pipeline, build servers and AI coding agent. The posts here come from errors seen in real deploys on the platform.

All posts by Brook →
On this page
  • Why does a proxy cause a redirect loop?
  • Quick checklist
  • How do you fix it in Express?
  • How do you fix it in Django?
  • How do you fix it in Laravel?
  • How do you fix it in Rails?
  • What about Next.js with NextAuth or Auth.js?
  • Why does Cloudflare Flexible SSL loop?
  • What happens on EthioDeploy?
  • Questions
  • Sources
0% read

Keep reading

  • engines.node

    Fix deploy errorsNov 24, 2026

    "The engine node is incompatible": fix Node version mismatches on deploy

    The error means the Node version running your install is outside a range in engines.node, either your own package.json or a dependency's. Yarn 1 stops on it by default; npm only warns unless engine-strict is on; pnpm warns for your project and fails for dependencies when engine-strict is set. Fix it by choosing the Node version on the build machine; loosening the check only hides the problem. Set engines.node to a bounded range such as "24.x", and check how your host reads it. Heroku and Vercel read engines.node, Render reads NODE_VERSION, .node-version and .nvmrc before it, and nixpacks reads NIXPACKS_NODE_VERSION before everything else and only knows whole majors. Run node -v in your build command to see what you actually got.

  • service_role

    Fix deploy errorsNov 24, 2026

    Leaked Supabase service_role key: what to do now

    A leaked service_role key gives anyone full access to your database, because it bypasses Row Level Security. Act in this order: create a new secret key (sb_secret_) and move your server code to it, switch browser code to a publishable key, deactivate the legacy anon and service_role keys under Settings > API Keys, then revoke the legacy JWT secret, since that secret is what makes the old key valid. Read your logs before they expire (one day on the Free plan), turn on RLS for every exposed table, and move the code that needed the key to a server so it never reaches the bundle again. Removing it from git history comes last and doesn't undo the leak.

  • exit 137

    Fix deploy errorsNov 24, 2026

    Container killed with exit code 137: OOM or SIGKILL?

    Exit code 137 is 128 + 9: the process was killed with SIGKILL. In a container that usually means it went over its memory limit and the kernel's OOM killer stopped it, but docker kill and a docker stop that ran out of patience give 137 too. Check with docker inspect: State.OOMKilled is true only for a memory kill. Then make the app fit: cap Node's heap below the container limit with --max-old-space-size, run fewer Python workers or recycle them with max_requests, stream large data instead of loading it, and give the build its own memory budget, separate from the running app.

EthioDeploy

Agentic first development and deployment, started in Ethiopia, built for developers everywhere.

Telegram community
Product
PricingAI coding agentAgent mode docsDomainsCLIFree backend hostingHosting in EthiopiaChangelog
Deploy guides
Next.jsNode.jsPythonSvelteKitTanStack StartAstroNuxtReact RouterHonoStrapiPayload CMSDjangoFastAPIFlaskStreamlitExpressNestJSLaravelRailsGoSpring BootASP.NET CoreTelegram botDiscord botWhatsApp botLovableBoltReplitv0Google AI StudioBase44Firebase StudioClaude Code & Cursor
Compare
vs Herokuvs Vercelvs Rendervs Railwayvs Fly.iovs Netlifyvs KoyebHeroku alternativesVercel alternativesNetlify alternativesRender alternativesRailway alternativesFly.io alternativesReplit alternativesPythonAnywhere alternativesDigitalOcean App Platform alternativesGlitch alternatives
Resources
DocsBlogFree toolsAboutSupportContactllms.txt
© 2026 EthioDeployPay by card in USD or bank transfer in ETBTermsPrivacy