How HTTP Redirects Actually Work (301 vs 302 vs 307)

Explains the functionality and use cases of common HTTP redirect status codes: │ 301 (Moved Permanently), 302 (Found/Temporarily Moved), and 307 (Temporary Redirect).

Beginner

HTTP redirects are a way to send users and search engines to a different URL than the one they originally requested. This is done by the server sending a specific HTTP status code to the client (browser), which then instructs the client to make a new request to the new URL.

Here's how the different types work:

1. 301 Moved Permanently

  • Purpose: Indicates that the requested resource has been permanently moved to a new URL.
  • Behavior: The browser will automatically redirect to the new URL and, importantly, will typically cache this redirect. This means that subsequent requests to the original URL will go directly to the new URL without hitting the old one first. Search engines also update their indexes to point to the new URL.
  • Method Change: The HTTP method (e.g., GET, POST) used in the original request might change from POST to GET in the redirected request, although modern browsers often preserve the method for 301s.
  • Use Cases: When a page has a new permanent address, changing domain names, or enforcing HTTPS.

2. 302 Found (Temporarily Moved)

  • Purpose: Indicates that the requested resource is temporarily located at a different URL. The server expects the client to continue using the original URL for future requests.
  • Behavior: The browser redirects to the new URL, but it does not cache the redirect. Future requests to the original URL will still go to the original server, which will then issue the 302 redirect again. Search engines generally do not update their indexes for 302 redirects.
  • Method Change: Historically, browsers would change the HTTP method from POST to GET for the redirected request, even if the original was a POST. This behavior is still common.
  • Use Cases: A/B testing, temporary landing pages, or when a resource is temporarily unavailable at its usual location.

3. 307 Temporary Redirect

  • Purpose: Similar to 302, it indicates that the requested resource is temporarily located at a different URL. The key difference is how it handles the HTTP method.
  • Behavior: The browser redirects to the new URL and does not cache the redirect.
  • Method Preservation: Crucially, a 307 redirect explicitly guarantees that the HTTP method used in the original request (e.g., GET, POST, PUT) will be preserved for the redirected request. If the original request was a POST, the redirected request will also be a POST.
  • Use Cases: When you need a temporary redirect and it's critical to preserve the original HTTP method, such as with form submissions. It's a more semantically correct alternative to 302 when method preservation is important.