Open Redirect Vulnerability: How to Fix It

By Bug Circuit Security Team
Open Redirect Vulnerability: How to Fix It

Is your own website affected? Check it free in 2 minutes.

Passive outside check only. Nothing is attacked, no signup.

An open redirect is a real vulnerability: it is usually rated low severity on its own, but attackers use it to make phishing links look like they come from your trusted domain, and the fix is to redirect only to destinations on an allowlist.

This post is for site owners and developers who have seen "open redirect" in a scan report and want to know if it matters. You will get a plain-English explanation, a vulnerable-versus-safe example, an allowlist fix for JavaScript, Java and C#, and a five-minute test you can run on your own redirect parameters.

Open redirect vulnerability explained

Many sites send visitors somewhere after an action. After login, you land on the page you wanted. After a click on an outgoing link, you go to a partner site. The destination is often stored in the URL, like this:

https://yoursite.com/login?next=/dashboard

The next value is a redirect parameter. An open redirect happens when your site accepts any destination there, including a different website, and sends the visitor along without checking:

https://yoursite.com/login?next=https://evil.example

The visitor clicks a link that starts with your real domain, and your server bounces them to a site the attacker controls. MITRE tracks this weakness as CWE-601. OWASP covers it in its Unvalidated Redirects and Forwards Cheat Sheet.

Is an open redirect a vulnerability?

Yes, but the severity depends on context. An open redirect does not let an attacker read your database or take over your server. It lets them borrow your good name.

On its own, it is often rated low. Some bug bounty programs even treat a standalone open redirect as out of scope. That does not make it harmless. Two things raise the risk:

  • Phishing. The link looks trustworthy because the domain is yours.
  • Chaining. Open redirects can help attackers get past weak checks in other features, such as login flows that use OAuth (the "Sign in with Google" style of login). If a flow sends a login token to a redirect address, a loose redirect rule can send that token to the wrong place.

The honest summary: fix it, because the fix is small and the downside is real, but do not panic.

How attackers use it for phishing

Here is a typical story, with made-up names:

  1. An attacker finds https://shop.example/go?url=... on your store. It redirects to whatever url says.
  2. They build a link: https://shop.example/go?url=https://shop-example-login.test.
  3. They email it to your customers: "Your order needs a quick check."
  4. The customer hovers over the link, sees your real domain, and clicks.
  5. Your server redirects them to a fake login page that looks like yours. They type their password.

Email filters and security tools often trust links that start with a known domain. Your reputation does the work for the attacker. This is why a "low" finding can still hurt customers.

Vulnerable vs safe: a simple example

This Node.js (Express) route is vulnerable. It trusts the next value completely:

app.get('/login/done', (req, res) => {
  res.redirect(req.query.next); // anything goes
});

The safe version checks the value first and falls back to a known page:

app.get('/login/done', (req, res) => {
  res.redirect(safeRedirectTarget(req.query.next, '/dashboard'));
});

The rule is simple. Never pass raw user input to a redirect. Validate it against something you control.

The best fix of all is to avoid URLs in parameters. Use a short name instead, like ?next=billing, and map it on the server to a fixed page. When you must accept a URL, use an allowlist.

The allowlist fix in JavaScript, Java and C#

An allowlist is a short list of approved destinations. Anything not on it is replaced with a safe default. Each example below parses the input like a URL, checks the scheme and host, and returns only the path. The code also rejects a returned path that begins with // or /\, because a browser reads that as a new host. That way the visitor stays on your own site. Replace example.com with your domain.

JavaScript (Node.js)

const ALLOWED_HOSTS = new Set(['www.example.com', 'example.com']);
const BASE = 'https://www.example.com';

function safeRedirectTarget(input, fallback = '/') {
  if (typeof input !== 'string') return fallback;
  try {
    const url = new URL(input, BASE); // relative paths resolve to BASE
    if (url.protocol !== 'https:' || !ALLOWED_HOSTS.has(url.hostname)) {
      return fallback;
    }
    const path = url.pathname + url.search + url.hash;
    // Reject any returned path that begins with // or /\
    if (path.startsWith('//') || path.startsWith('/\\')) return fallback;
    return path;
  } catch {
    return fallback; // not a valid URL
  }
}

Java

import java.net.URI;
import java.util.Set;

public final class Redirects {
    private static final Set<String> ALLOWED_HOSTS =
        Set.of("www.example.com", "example.com");
    private static final URI BASE = URI.create("https://www.example.com/");

    public static String safeRedirectTarget(String input, String fallback) {
        if (input == null || input.isBlank() || input.contains("\\")) {
            return fallback;
        }
        try {
            URI target = BASE.resolve(input.trim());
            if (!"https".equalsIgnoreCase(target.getScheme())
                    || target.getHost() == null
                    || !ALLOWED_HOSTS.contains(target.getHost().toLowerCase())) {
                return fallback;
            }
            String path = target.getRawPath();
            if (path == null || path.isEmpty()) path = "/";
            // Reject any returned path that begins with // or /\
            if (path.startsWith("//") || path.startsWith("/\\")) return fallback;
            return target.getRawQuery() == null ? path : path + "?" + target.getRawQuery();
        } catch (IllegalArgumentException e) {
            return fallback; // malformed input
        }
    }
}

In Spring MVC, return "redirect:" + Redirects.safeRedirectTarget(next, "/dashboard").

C# (ASP.NET Core)

private static readonly HashSet<string> AllowedHosts =
    new(StringComparer.OrdinalIgnoreCase) { "www.example.com", "example.com" };
private static readonly Uri Base = new("https://www.example.com");

public static string SafeRedirectTarget(string input, string fallback = "/")
{
    if (string.IsNullOrWhiteSpace(input)) return fallback;
    if (!Uri.TryCreate(Base, input, out var uri)) return fallback;
    if (uri.Scheme != Uri.UriSchemeHttps || !AllowedHosts.Contains(uri.Host))
        return fallback;
    var local = uri.PathAndQuery;
    // Reject any returned path that begins with // or /\
    if (local.StartsWith("//", StringComparison.Ordinal)
        || local.StartsWith("/\\", StringComparison.Ordinal))
        return fallback;
    return local;
}

If you only need local redirects, ASP.NET Core already has a built-in helper. Use LocalRedirect(returnUrl) or check Url.IsLocalUrl(returnUrl) before redirecting. Microsoft explains this in its guide to preventing open redirect attacks.

Notes that apply to all three

  • Compare the parsed host to the list. Do not compare raw text.
  • Allow only https:. This blocks javascript: and other odd schemes.
  • Reject any returned path that begins with // or /\. A host check alone is not enough.
  • Return a fixed fallback page when the check fails. Do not show the attacker's value back in an error.
  • Log blocked attempts. A burst of them tells you someone is probing.

Common "fixes" that fail

Many open redirect patches look right and still break. Browsers and servers read URLs more loosely than most developers expect.

Weak checkWhy it failsExample bypass
Value starts with /A double slash is read as a new host//evil.example
Value starts with https://yoursite.comAnyone can register a longer domainhttps://yoursite.com.evil.example
Value contains yoursite.comThe text can appear anywherehttps://evil.example/?yoursite.com
Blocklist of bad domainsYou cannot list every bad domainA new domain the next day
Check done before decodingThe URL is decoded laterEncoded slashes or backslashes
Host is checked but the returned path is notA path starting with // is read as a new hosthttps://yoursite.com//evil.example

Parse first, check the host against an exact allowlist, and make sure the path you return does not start with // or /\. That closes these bypasses.

For OAuth and single sign-on, register exact redirect addresses with the provider and require an exact match. Do not allow wildcards or partial matches.

A quick test for your own redirect parameters

Only test sites you own or have written permission to test. This takes about five minutes.

  1. Find redirect parameters. Look for URLs with names like next, url, redirect, return, returnUrl, continue, goto, dest or redirect_uri. Check your login, logout, language-switch and "outgoing link" pages.
  2. Try an outside address. Open this in a browser, using example.org (a domain reserved for examples):

https://yoursite.com/login?next=https://example.org

  1. Check the response with curl. Look at the Location header:

curl -sI "https://yoursite.com/login?next=https://example.org" | grep -i '^location'

  1. Try the sneaky variants. Test each of these as the parameter value:
  • //example.org
  • /%5Cexample.org (an encoded backslash)
  • https://yoursite.com.example.org
  • https://yoursite.com@example.org
  • https://yoursite.com//example.org
  1. Read the result. If Location points at example.org for any of them, you have an open redirect. If it stays on your site or goes to your fallback page, you are in good shape.

The free Bug Circuit website security check gives you a passive look at your domain from the outside. For redirect logic inside login flows, you need hands-on testing. See manual vs automated penetration testing for why tools often miss these cases. If you already suspect customers got phished through your domain, read what to do on the website hacked page.

Extra layers worth adding

These do not replace the allowlist. They reduce the damage if something slips through.

  • Warn on external links. For outgoing links that must exist, show a page saying "You are leaving our site" with a confirm button.
  • Sign the redirect. If you need flexible destinations, include a signed token (an HMAC) so only links your server created will work.

Key takeaways

  • An open redirect is a real but usually low-severity flaw. Its main danger is phishing and chaining with login flows.
  • Never redirect to raw user input. Prefer short names mapped to fixed pages.
  • When you need URLs, parse them, require https:, compare the host to an exact allowlist, and reject any returned path that starts with // or /\.
  • Weak checks such as startsWith, contains and blocklists are easy to bypass.
  • Test every redirect parameter with //example.org, https://yoursite.com//example.org and look-alike hosts, and only on sites you own.

Want a human to check your redirects?

If you would like a person to test your login flow and redirect parameters, the Essential plan is $49 one-time. It covers 1 website with 3 manual audits to request within one month. Each audit ends in a written report with every issue, its severity, evidence and fix steps.

It is a focused small-site audit, not a compliance certification or a multi-week enterprise pentest. Bug Circuit reports problems and explains the fix. Fixing is a separate service, quoted per issue, and you pay only if you agree to the price.

Want certainty, not guesswork?

A real human security engineer audits your whole site by hand and sends a full report: every issue, its severity, and the exact fix. From $49, with a 14-day money-back guarantee.

See pricing

Frequently asked questions

Is open redirect a vulnerability?
Yes. It is a recognized weakness (CWE-601). It is usually rated low severity on its own because it does not expose data directly. It still matters because attackers use it to make phishing links look like they come from your trusted domain.
How do I fix an open redirect vulnerability?
Stop sending users to raw input. Use short names mapped to fixed pages, or parse the URL, require https, and compare the host to an exact allowlist. Also reject any returned path that starts with // or /\. Send anything else to a safe default page. Do not rely on startsWith, contains or blocklists.
How do I test for an open redirect?
On a site you own, find parameters like next, url or redirect, and set them to https://example.org. Then run curl -sI on the URL and read the Location header. Also try //example.org, https://yoursite.com//example.org and look-alike hosts. If the Location header points outside your site, it is open.
Can an open redirect be used to steal login tokens?
It can help in some cases. If a login flow such as OAuth accepts loose redirect addresses, an attacker may be able to send a token or code to a place they control. Register exact redirect addresses with your login provider and require an exact match.
Do security scanners find open redirects?
Some do, especially simple cases where a parameter sends users to any outside address. Scanners often miss redirects hidden behind a login or built from several steps. A manual tester can follow those flows and try bypasses that tools skip.

Keep reading

See what attackers see, for free

Run the free passive check on your website. No login, no impact on your site, results in seconds.

Ready for the full manual audit? See pricing

Published by Bug Circuit. Written with AI assistance and reviewed for accuracy before publishing.