URLs · 11 min read

How to Encode a Redirect URL Inside a Query Parameter

Putting a whole URL inside another URL without the two layers of syntax bleeding into each other comes down to one encoding decision, made exactly once.

Abstract illustration of a shape nested inside a larger shape

Redirect flows are everywhere once you start looking for them. A login page needs to know where to send you afterward. A payment processor needs a return address. A relay service needs to hand you off to the next hop. In every one of these cases, the same structural problem appears: a complete URL, with its own scheme, path, and query string, has to travel as a single value inside another URL's query string.

Get it right and the flow works invisibly. Get it wrong and the redirect silently loses half its parameters, or the server rejects the request outright, or — worst of all — the flow appears to work in your one test case and breaks the moment the target URL contains a character you did not anticipate. This guide walks through exactly why the naive approach fails, the one rule that fixes it, and how to handle the decode side without recombining the layers incorrectly.

The problem: a URL has to live inside another URL

Suppose your application needs to send the user to a login endpoint, and after authentication the login endpoint should redirect them to this callback address:

https://app.example.com/callback?state=abc&scope=read

The obvious instinct is to paste that address onto the end of the login URL as a parameter named, say, next:

https://auth.example.com/login?next=https://app.example.com/callback?state=abc&scope=read

It looks plausible. It is not. It is broken in a way that is worth understanding precisely, because the failure mode teaches you everything about how URL syntax works.

What breaks when you paste it in raw

A query string is a flat sequence of key-value pairs separated by &, with = separating each key from its value. There is no nesting in that grammar. No bracket, no quoting mechanism, no notion of "this chunk belongs to that parameter." When the server at auth.example.com parses the query string above, it does not see one parameter whose value happens to contain a URL. It sees this:

next = https://app.example.com/callback?state=abc
scope = read

The inner & — the one that belonged to the callback URL — has split the outer query string in two. The next parameter is truncated mid-URL, losing everything after state=abc. The scope parameter, which the login server never asked for, appears out of nowhere. And if the inner URL had contained more parameters, each one would have peeled off into its own garbage key at the outer level.

The inner = and ? cause quieter damage. Many parsers tolerate a second = inside a value by treating only the first one as the separator, but that behavior is a courtesy, not a guarantee. The ? in the middle of a query value is flatly invalid, and strict parsers will reject the whole request. Meanwhile the inner : and // are technically permitted in a query string under RFC 3986, but they make the value ambiguous to any intermediate system that tries to interpret it as a URL.

In short: the moment you inserted the inner URL raw, its syntax stopped belonging to it. Every reserved character in the inner URL — &, =, ?, # if there were a fragment — got reinterpreted as outer syntax.

What makes this class of bug especially unpleasant is that it is invisible at the point of construction. Building the URL never fails; the string concatenates happily. The failure happens later, at parse time, on a machine you do not control, and it manifests as symptoms that look unrelated to their cause: a missing scope on the callback, a session that cannot be matched to its state value, a log line showing a redirect target that is cut off mid-parameter. By the time you are reading stack traces, the innocent-looking concatenation from three calls ago is long out of mind. Understanding the parse order is the only way to diagnose it quickly.

The rule: the inner URL is one value, so encode it like one value

Here is the entire fix, stated once: the inner URL is a single value of the outer query string, so it must be encoded with component-level encoding — the kind applied to one complete value, not to a URL as a whole. In JavaScript terms, that means encodeURIComponent semantics, not encodeURI semantics. If you are unsure why that distinction matters, the guide on encodeURI versus encodeURIComponent covers it in depth.

Component-level encoding takes every character that is special in a query string and replaces it with its percent-encoded form:

  • & becomes %26 — so it can no longer split the outer query
  • = becomes %3D — so it can no longer split key from value
  • ? becomes %3F — so it can no longer start a fake second query
  • : becomes %3A and / becomes %2F — so the scheme and path separators lose their special meaning at the outer level
  • # becomes %23 — so a fragment inside the inner URL cannot terminate the outer one

After encoding, the callback URL from earlier looks like this:

https%3A%2F%2Fapp.example.com%2Fcallback%3Fstate%3Dabc%26scope%3Dread

And the complete, correct login URL is:

https://auth.example.com/login?next=https%3A%2F%2Fapp.example.com%2Fcallback%3Fstate%3Dabc%26scope%3Dread

Now the outer query string has exactly one parameter, next, whose value is an opaque string. The ampersands and equals signs inside the inner URL are safely frozen as %26 and %3D. Nothing bleeds between the layers.

Building it in code

The construction side is a one-liner in any language. In JavaScript:

const target = "https://app.example.com/callback?state=abc&scope=read";
const loginUrl = "https://auth.example.com/login?next=" + encodeURIComponent(target);

The same principle applies in any stack: take the full inner URL as one string, apply the equivalent of component encoding to that entire string, then concatenate it onto the outer URL as one parameter value. What you must never do is encode the inner URL "a little bit" — for example, escaping only the ampersands and leaving the rest raw. Partial encoding produces a value that some parsers handle and others mangle, which is precisely the kind of bug that surfaces in production rather than in testing. If you have ever seen a redirect where the target arrived with stray plus signs where spaces used to be, that is a sibling of this problem; the guide on plus signs and spaces explains that particular trap.

What each layer looks like after encoding

It helps to keep an explicit picture of the two layers and their separate encoding states, because confusion between them is the root cause of both under-encoding and over-encoding.

LayerValueEncoding state at the outer parser
Outer URL (login endpoint)https://auth.example.com/login?next=...Plaintext. Its own syntax — the ?, the = after next — is live and parsed.
Inner URL (app callback)https://app.example.com/callback?state=abc&scope=readEncoded once at component level. Every reserved character is frozen as %3A, %2F, %3F, %3D, %26.
Inner-inner values (state=abc, scope=read)abc, readStill plaintext inside the encoded layer. They are only decoded when the inner URL is decoded and parsed on its own.

The last row is the one people find counterintuitive. You do not encode abc or read at the outer level, and you do not need to — they are protected by the single encoding of the layer above them. Each layer's encoding job is only to make its own structure opaque to the layer outside it.

The decode side: read the outer parameter first

Decoding has a strict order, and violating it is the second most common way these flows break. The rule: parse the outer URL first, extract the parameter as a decoded string, and only then do you have the inner URL standing alone.

In practice, most server frameworks do the outer decode for you. When you read next out of the parsed query, you get back the original inner URL, fully reconstructed:

const next = new URL(request.url).searchParams.get("next");
// next === "https://app.example.com/callback?state=abc&scope=read"

At this point next is an ordinary URL with live syntax again. Its & separates its own parameters; its = pairs keys with values. You can parse it with a normal URL parser and read state and scope out of it.

The mistake to avoid is decoding the entire outer URL in one pass — for example, running a global percent-decode over the whole request URL, or over the raw query string, before parsing it. If you do that, the %26 inside the next value turns back into a live & before the outer parser runs, and you are right back to the broken parse from the start of this guide: the outer query splits into garbage parameters, and the inner URL's structure has recombined into the outer layer. Decode order must mirror encode order, inside-out in reverse: outer parse, then extract, then — and only if you need to inspect the inner URL's own parameters — parse the inner URL as its own document.

There is a practical corollary worth writing down: a value you extract from a parsed query is already decoded, and it does not need a second decode. If the extracted next still contains visible %3A or %26 after you read it, that means it was encoded twice upstream — a defect in the producer, which you should fix at the source rather than paper over with another decode call on the consumer side. Layers should be symmetric: one encode per wrap, one decode per unwrap, and nothing in between.

Encode once, decode once. If you find yourself running decodeURIComponent twice on a value, or encoding the same URL at two different points in the pipeline, stop and check whether you are drifting into double encoding. The guide on double URL encoding covers what happens when the layers get encoded twice and how to unwind it.

When nesting goes deeper than two layers

Real flows sometimes stack three or more hops. A common shape: a login endpoint redirects to a relay or continuation service, which finishes some processing and then redirects to the final callback. Each hop receives a target URL as a parameter and must pass it (or a further target) along.

The discipline is the same at every level, applied one layer at a time. Build from the inside out:

const finalTarget = "https://app.example.com/callback?state=abc&scope=read";

// Layer 2: the relay's URL wraps the final target
const relayUrl = "https://relay.example.com/continue?to=" + encodeURIComponent(finalTarget);

// Layer 1: the login URL wraps the relay URL
const loginUrl = "https://auth.example.com/login?next=" + encodeURIComponent(relayUrl);

The resulting next parameter now contains the relay URL, which itself contains the encoded form of the final target — the final target's percent signs have been encoded again into %253A and so on at the outermost layer. That is correct, not a bug: each layer of wrapping applies one more round of encoding to everything beneath it, and each layer of unwrapping removes exactly one round.

Keeping track of this across a multi-hop flow is mostly a bookkeeping exercise, and it pays to be systematic:

  • At each hop, the service receives exactly one level of encoded input, decodes it once by parsing its own query, and treats the result as a complete, live URL.
  • When forwarding to the next hop, that live URL gets encoded exactly once more as a single parameter value.
  • Never pass a still-encoded value through unchanged and then encode it again on top — that is how spurious extra layers appear.
  • Never decode a value "to be safe" before re-encoding it at the same level — one layer in, one layer out, every time.

A useful sanity check while debugging: count the rounds of percent-encoding visible in the parameter at each stage of the flow. It should decrease by exactly one at every decode step and increase by exactly one at every wrap step. If it ever changes by two, or stays flat when it should have changed, you have found your defect.

Where you will meet this pattern

Once you know the shape, you see it across the industry. The best-known example is the redirect_uri parameter in OAuth-style authorization flows: the client registers a callback address, and that address — often carrying its own query parameters such as state — must ride as a single encoded value inside the authorization request. The authorization server decodes it once, validates it against the registered value, and later sends the user's browser to it. The specification-level requirements around redirect_uri exist precisely because naive handling of this nesting creates real vulnerabilities.

Countless frameworks and sites use the same idea under other names: a returnTo, continue, next, or return_url parameter that carries the post-action destination. Payment providers, email-confirmation links, multi-step wizards, and SSO relays all lean on the identical mechanism. The syntax rules never change, only the parameter names do — so the encode-once rule from this guide transfers directly, whatever the label happens to be.

Security: decoding is for inspection, not blind trust

One warning belongs in every discussion of redirect parameters, and it is not about syntax. A URL that arrives in a query parameter is attacker-controlled input. Anyone can craft a link like:

https://auth.example.com/login?next=https%3A%2F%2Fevil.example.net%2Fphish

The encoding is perfectly correct. The target is perfectly malicious. If your server reads next, trusts it, and issues a redirect, you have built an open redirect: an endpoint on your domain that forwards users anywhere an attacker wants, complete with a legitimate-looking origin in the browser bar at the first hop. Open redirects are used for phishing, for laundering malicious links through trusted domains, and in some OAuth misconfigurations for stealing authorization codes.

So the decode step is for inspection, and inspection must be followed by validation before navigation:

  • Decode the parameter, parse it as a URL, and check the scheme — allow only https (or http strictly for local development). Reject anything else outright.
  • Check the host against an allowlist of domains you control or have explicitly approved. Substring matching is not enough; evil-example.com is not example.com.
  • Do not follow the redirect server-side to "see where it goes." Validate the target itself, at the layer where you received it.
  • When validation fails, fall back to a safe default destination rather than rejecting the user outright.

The encode-once rule keeps the layers from bleeding into each other. Validation keeps the decoded layer from being a weapon. You need both.

Checklist

  • The inner URL is treated as one complete value, never spliced into the outer query raw.
  • It is encoded once, at component level — every reserved character (&, =, ?, #, :, /) percent-encoded.
  • Not encoded twice at the same layer; each additional nesting level adds exactly one more round.
  • On the way back, the outer URL is parsed first, the parameter extracted, and only then is the inner URL handled as a live URL.
  • No global decode is applied to the whole outer URL before parsing.
  • Multi-hop flows encode exactly once per wrap and decode exactly once per unwrap, with the visible encoding depth decreasing by one at each step.
  • The decoded target is validated — scheme allowlisted, host allowlisted — before any redirect is issued.
  • Failed validation falls back to a safe default, not a silent pass-through.

Test it yourself

The fastest way to internalize this is to watch a real URL go through the transformation. Take the broken example from the top of this guide, then rebuild it correctly, and compare how each one parses. The URL Workbench on the routineza workbench lets you paste both versions, split the query string, and see exactly where the raw version falls apart into garbage parameters while the encoded version holds together as a single clean value. Try decoding the encoded parameter once — you should recover the inner URL intact — and then try decoding the whole outer URL in one pass to watch the layers recombine incorrectly. Ten minutes of that exercise teaches more than any diagram.

Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.