How to Handle HTTP Redirects Safely
Choose the right redirect status, avoid open redirects, preserve methods across 307 and 308, and prevent redirect loops and header leakage.
On this page
Introduction
A redirect is a response that tells the client to fetch a different URL instead. The mechanism is used constantly for HTTP to HTTPS upgrades, trailing-slash normalization, moved pages, and post-login navigation. It is also a reliable source of subtle bugs: a redirect that silently turns a POST body into nothing, one that loops forever, and one that trusts a user-supplied destination and becomes an open redirect are all common. A redirect is simple in syntax and demanding in semantics.
This tutorial covers the four main redirect codes and when each is correct, how to prevent open redirects, how to preserve request methods, how to bound redirect chains, and how to test each behavior. The examples use Node.js, but the status semantics are protocol-level and apply to any language or framework.
Choose the correct status code
The permanent codes are 301 and 308, and the temporary ones are 302 and 307. The second pair is the method question: 302 historically allowed clients to change a POST into a GET, and 307 was introduced to preserve the method and body. Likewise 308 is the permanent, method-preserving counterpart of 301. For an HTTP to HTTPS upgrade or a moved page that never comes back, use a permanent code so clients and search engines update their links. For a login redirect or a maintenance page, use a temporary code so the client does not cache the destination.
The method-preservation distinction matters most for non-idempotent requests. If a POST to create an order is answered with a 302 and the client converts it to a GET at the new location, the order is not created. Returning 307 or 308 keeps the method, so the client repeats the POST with the same body, which is why these are the correct choices when a submit has to move. For a plain GET, either pair works and the cache lifetime becomes the deciding factor.
Prevent open redirects
An open redirect turns your domain into a springboard for phishing: an attacker sends a link that appears to be yours, it redirects to a look-alike login page, and the victim trusts the address bar. The vulnerability appears whenever a redirect target is taken from user input, commonly a next or returnTo query parameter used for post-login navigation. Never redirect to a raw value from the request.
Two defenses work together. First, prefer indirect targets: instead of accepting a URL, accept an opaque key that the server maps to a fixed destination. Second, if a URL must be accepted, parse it and allow only relative paths, or allow absolute URLs only when the host is on an explicit allowlist. Reject values with a scheme such as javascript: or data:, and reject anything with a host that differs from yours.
const ALLOWED_HOSTS = new Set(['app.example.com']);
function safeRedirectTarget(next: string | undefined): string {
if (!next) return '/';
let url: URL;
try {
url = new URL(next, 'https://app.example.com');
} catch {
return '/';
}
if (url.protocol !== 'https:') return '/';
if (url.host !== 'app.example.com' && !ALLOWED_HOSTS.has(url.host)) return '/';
return url.pathname + url.search;
}
Preserve methods and bodies
When the client follows a 307 or 308, it resends the same method and body to the new location. Design the endpoint to accept that repeat, which connects to idempotency: a moved POST should still be safe to replay where appropriate. If the destination is a different origin, some clients strip the Authorization header and cookies as a security measure, so a redirect that crosses origins can silently drop credentials and fail. Keep redirects to the same origin unless crossing is intentional.
For APIs, prefer to return the new URL in a Location header with a 201 or 202 rather than a redirect at all. Many HTTP clients do not follow redirects by default for API calls, and a 3xx can be mistaken for success. Redirects are for browsers and simple clients; a JSON API is usually clearer with an explicit status and a body that names the new resource.
import { createServer } from 'node:http';
createServer((req, res) => {
if (req.url === '/old-path') {
// permanent move, preserve method
res.writeHead(308, { location: '/new-path' });
res.end();
return;
}
if (req.url === '/login' && req.method === 'POST') {
// temporary, browser only; do not let the client cache it
res.writeHead(303, { location: '/dashboard', 'cache-control': 'no-store' });
res.end();
return;
}
res.writeHead(200).end('ok');
}).listen(3000);
Bound redirect chains and loops
A redirect that points to a URL which redirects back creates an infinite loop. The client eventually aborts after a hop limit, and in the meantime it hammers both endpoints. Prevent loops at the source by never redirecting a request that already arrived via a redirect when the only difference is a cosmetic one, and by checking that the target does not redirect back. On the client side, always set a maximum number of redirects so a misconfiguration does not become a denial-of-service.
Watch out for the redirect that preserves a difference forever: adding a trailing slash on a URL that already has one, or redirecting http to https on a request that is already https. These loops are usually caused by a normalization rule that does not check the current state before applying the redirect.
Test redirect behavior
Test each redirect with a method that proves preservation. Send a POST to the moved endpoint and assert the client receives a 307 or 308 and resends the POST. Send a crafted next parameter pointing at an external host and assert the server ignores it and uses a safe default. Follow a chain long enough to trigger the loop guard and assert it aborts rather than recursing forever.
# method preservation
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -X POST http://localhost:3000/old-path
# open-redirect defense: try to escape to an external host
curl -s -o /dev/null -w '%{redirect_url}\n' 'http://localhost:3000/login?next=https://evil.example.com'
Common pitfalls
Using 302 for a submit and losing the body, trusting a user-supplied redirect target, forgetting that a cross-origin redirect drops credentials, caching a temporary redirect, and creating a normalization loop are the recurring mistakes. Each maps to a status-code rule, a validation rule, or a loop guard, and a small shared redirect helper can enforce all of them consistently instead of re-deciding at each endpoint.
Conclusion
Redirects are easy to emit and easy to get wrong. Choose permanent versus temporary by intent, choose the method-preserving code when a body matters, never build a target from raw user input, bound the chain, and drop credentials only deliberately. Self-check by sending a POST through the moved route and confirming the method survives, and by sending an external next value and confirming it is rejected. A tested redirect helper keeps both the usability and the security property intact.
Sources: MDN: Redirections in HTTP, RFC 9110: Redirection status codes, OWASP: Unvalidated redirects and forwards.
FAQ
- When should I use 307 instead of 302?
- 302 lets clients change the method, and many turn a POST into a GET on the redirected request, which loses the body. 307 guarantees the method and body are preserved, so use it when a temporary move must not alter the request semantics.
- How do I stop an open redirect?
- Never build a redirect target directly from a query parameter. Either map an identifier to a server-controlled path, or validate the target against an allowlist of hosts and reject absolute URLs that point elsewhere.
Report a problem with this articleOpens a pre-filled issue on GitHub.