Open Redirect Protection
What it does
Intercepts all 3xx redirect responses and validates the Location header, as well as the Refresh header of any response (Refresh: 5; url=… also sends the browser elsewhere, whatever the status).
If the redirect destination is an external host not in the allowed list, the middleware returns HTTP 400.
Protects against phishing attacks where an attacker crafts a link like
https://yoursite.com/login?next=https://evil.com that silently redirects users elsewhere.
How it works
A redirect destination is considered safe if:
- It is a relative path (
/dashboard,../profile) — always safe - The host is localhost or loopback (
localhost,127.x.x.x,[::1], IPv4-mapped IPv6) — always safe - The host matches an entry in
with_allowed_hosts(exact or wildcard subdomain)
Any other absolute URL is blocked with HTTP 400.
Configuration
No dedicated configuration — the middleware reads with_allowed_hosts automatically:
.middleware(|m| {
m.with_allowed_hosts(|h| {
h.host("example.com")
.host(".example.com") // example.com + all subdomains
})
})
The open redirect middleware is always active and uses the same host list.
Protocol-relative URLs
URLs starting with // (e.g. //evil.com/path) are treated as absolute and subject to the same check.
They are blocked unless the host is in the allowed list.
The destination is read the way a browser reads it (WHATWG URL parser): \ counts as /, tabs and newlines are dropped, credentials (user@host) are split from the host. /\evil.com or /\t/evil.com therefore do lead to evil.com, and are blocked. A scheme other than http / https (javascript:, data:) is always refused.