
Preventing Unsafe HTTP Redirect Handling in Rust: Validating Locations, Preserving Method Semantics, and Avoiding Open Redirects
Why redirect handling matters
Redirects are common in login flows, payment providers, SSO, API gateways, and content fetchers. They are also a frequent source of security bugs:
- Open redirects: your app sends users to attacker-controlled destinations.
- Server-side request forgery (SSRF) amplification: a trusted client follows redirects into internal networks.
- Credential leakage: authorization headers or cookies are forwarded to a different origin.
- Method confusion: a
POSTbecomes aGET, or a307/308preserves a sensitive method unexpectedly. - Redirect loops and hop abuse: unbounded following causes resource exhaustion.
The safest pattern is to treat every redirect as untrusted input and validate it before following.
Understand the redirect status codes
Not all redirects behave the same way. The status code determines whether the client may rewrite the method and body.
| Status | Typical meaning | Method/body behavior |
|---|---|---|
| 301 | Moved Permanently | Often rewritten to GET by clients |
| 302 | Found | Often rewritten to GET by clients |
| 303 | See Other | Forces GET |
| 307 | Temporary Redirect | Preserves method and body |
| 308 | Permanent Redirect | Preserves method and body |
For security-sensitive requests, 307 and 308 deserve special attention because they can forward a POST body to a new location. If that location is not fully trusted, the redirect becomes a data exfiltration path.
Use a redirect policy instead of blind following
If you use reqwest, the default redirect behavior is convenient but not always appropriate. A safer approach is to install a custom policy that inspects each Location header before the client follows it.
The policy should enforce rules such as:
- only allow
https - only allow a known host or domain suffix
- reject IP literals and private network ranges
- limit the number of hops
- disallow scheme changes
- strip sensitive headers on cross-origin redirects
Example: validating redirect targets with reqwest
use reqwest::{redirect::Policy, Url};
use std::time::Duration;
fn is_allowed_redirect(url: &Url) -> bool {
match url.scheme() {
"https" => {}
_ => return false,
}
let host = match url.host_str() {
Some(h) => h,
None => return false,
};
// Example allowlist: exact host or trusted subdomain.
host == "auth.example.com" || host.ends_with(".example.com")
}
fn main() -> Result<(), reqwest::Error> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.redirect(Policy::custom(|attempt| {
let next = attempt.url();
if attempt.previous().len() >= 5 {
return attempt.stop();
}
if !is_allowed_redirect(next) {
return attempt.stop();
}
attempt.follow()
}))
.build()?;
let response = client
.get("https://auth.example.com/start")
.send()?;
println!("Final status: {}", response.status());
Ok(())
}
This example shows a simple allowlist, but in production you should also reject suspicious hosts such as localhost, 127.0.0.1, ::1, and RFC1918 addresses if your application ever accepts user-controlled URLs.
Prevent open redirects in your own application
Open redirect vulnerabilities usually appear in endpoints like /login?next=... or /continue?return_to=.... The bug is often not in the HTTP client; it is in the application that reflects an untrusted URL into a Location header.
A safe redirect endpoint should accept only relative paths or a strict allowlist of destinations.
Unsafe pattern
use axum::{extract::Query, http::StatusCode, response::Redirect};
use serde::Deserialize;
#[derive(Deserialize)]
struct NextParam {
next: String,
}
async fn login_redirect(Query(params): Query<NextParam>) -> Redirect {
Redirect::to(¶ms.next)
}
This is dangerous because an attacker can supply https://evil.example/phish.
Safer pattern
use axum::{extract::Query, response::Result, http::StatusCode};
use serde::Deserialize;
#[derive(Deserialize)]
struct NextParam {
next: Option<String>,
}
fn sanitize_next(next: &str) -> Option<&str> {
if next.starts_with('/') && !next.starts_with("//") {
Some(next)
} else {
None
}
}
async fn login_redirect(Query(params): Query<NextParam>) -> Result<axum::response::Redirect, StatusCode> {
let target = params.next.as_deref().unwrap_or("/dashboard");
let safe = sanitize_next(target).ok_or(StatusCode::BAD_REQUEST)?;
Ok(axum::response::Redirect::to(safe))
}
This version only accepts relative paths and rejects scheme-relative URLs such as //evil.example, which browsers interpret as external destinations.
Preserve trust boundaries across origins
A redirect to a different origin should usually be treated as a new trust boundary. That means you should not automatically forward:
Authorization- session cookies
- CSRF tokens
- custom API keys
- internal tracing headers that reveal infrastructure details
Many HTTP clients will not forward all headers across origins by default, but you should not rely on defaults alone. If you manually reissue requests after inspecting redirects, explicitly rebuild the request and attach only the headers that are safe for the new destination.
Practical rule
| Redirect type | Safe to follow automatically? | Notes |
|---|---|---|
Same-origin https://app.example.com → https://app.example.com | Usually yes | Still cap hop count |
Subdomain change app.example.com → cdn.example.com | Maybe | Verify cookie scope and auth policy |
Cross-origin example.com → other.com | Usually no | Re-evaluate trust and headers |
Scheme downgrade https → http | No | Reject outright |
If your application handles secrets, a cross-origin redirect should be an explicit decision, not an automatic convenience.
Defend against SSRF through redirects
Redirects can turn a harmless-looking URL into an internal network request. For example, a user submits https://public.example/redirect, and that endpoint issues a 302 to http://169.254.169.254/latest/meta-data/.
To reduce this risk:
- Validate the initial URL before making the request.
- Validate each redirect hop.
- Reject private, loopback, link-local, and metadata IP ranges.
- Disallow DNS rebinding surprises by resolving and checking the final destination if your threat model requires it.
- Limit redirects to a small number, such as 3 to 5.
If you need strong SSRF resistance, consider resolving the host and checking the resulting IP address against a denylist of internal ranges before each hop. That is more robust than checking hostnames alone.
Handle relative and absolute Location values carefully
The Location header may contain:
- an absolute URL:
https://example.com/path - a relative path:
/path - a scheme-relative URL:
//example.com/path - a malformed value
Do not assume that a string beginning with / is always safe. //evil.example is not a relative path in browser semantics; it inherits the current scheme and changes the host.
A good validator should parse the target with a URL parser, resolve relative URLs against a trusted base, and then apply policy checks to the resolved result.
Example validation checklist
- Parse with
url::Url - Resolve relative references against the current origin
- Require
https - Require an allowlisted host or suffix
- Reject userinfo such as
https://user:pass@host - Reject IP literals unless explicitly allowed
- Reject ports outside an allowlist
Choose a redirect strategy based on the use case
Different applications need different policies. The table below summarizes common strategies.
| Use case | Recommended policy | Reason |
|---|---|---|
| Browser-facing login flow | Allow only relative redirects | Prevent open redirects |
| Backend API client | Allow same-origin redirects only | Preserve auth boundary |
| Third-party OAuth/OIDC client | Allow only provider-owned domains | Avoid token leakage |
| Content fetcher | Follow limited redirects with SSRF checks | Handle canonical URLs safely |
| Internal service-to-service calls | Disable redirects unless required | Keep routing explicit |
The safest default is usually do not follow redirects automatically unless the business case requires it.
Test redirect behavior explicitly
Security bugs in redirect handling are often regression-prone. Add tests that cover both accepted and rejected cases.
Useful test cases include:
https://trusted.example/pathis allowedhttp://trusted.example/pathis rejectedhttps://evil.example/pathis rejected//evil.example/pathis rejectedhttps://127.0.0.1/is rejected- redirect chains stop after the configured hop limit
- cross-origin redirects do not carry authorization headers
If you use integration tests, simulate a server that returns different Location headers and verify the client’s final destination and header behavior.
Operational best practices
A secure redirect implementation is not just code; it is also policy and observability.
- Log redirect decisions without secrets: record the source host, destination host, and reason for rejection.
- Expose metrics: count rejected redirects, hop-limit hits, and cross-origin attempts.
- Document allowed destinations: make the policy visible to reviewers and operators.
- Review redirect endpoints in code audits: especially
next,return_to,continue, andredirect_uriparameters. - Prefer explicit allowlists over regex-based host checks when possible.
If your application integrates with external identity providers or payment gateways, maintain a dedicated list of approved redirect domains and revisit it during vendor changes.
A practical security checklist
Before shipping redirect logic in Rust, verify the following:
- [ ] Redirect targets are parsed, not string-concatenated
- [ ] Only trusted schemes are allowed
- [ ] Hostnames are allowlisted or strictly constrained
- [ ] Private and loopback addresses are rejected
- [ ] Scheme downgrades are blocked
- [ ] Redirect chains have a low hop limit
- [ ] Sensitive headers are not forwarded cross-origin
- [ ] Open redirect endpoints accept only relative paths or allowlisted destinations
- [ ] Tests cover malicious
Locationvalues