301
vs 302
vs 307
vs 308
)?I'm working on building a web app and I'm a bit confused about the differences between HTTP status codes related to redirects, specifically 301
, 302
, 307
, and 308
.
From what I understand, 301
and 302
are common older codes, but I keep seeing 307
and 308
in documentation. What exactly is the difference between these four codes, what's their semantic meaning, and when should each be used (and/or not used)?
Historically many clients changed POST requests to a GET when following 301
or 302
redirects. For this reason, the more modern 307
and 308
redirect status codes were created to ensure that the request method is preserved by the client when following the redirect.
These redirect codes indicate that the requested resource has permanently moved to a new URL. Browsers may cache these redirects much more aggressively than temporary redirects and you should use them when you don't expect the redirect location to change, or for the page to return content itself in the near future.
301
- Moved Permanently: Historically, clients changed a POST to a GET when following a 301
, although this was not required by the original spec.308
- Permanent Redirect: 308
serves the same purpose as 301
, but guarantees the client will never change request method automatically (POST stays POST).On the other hand, these redirect codes indicate that the requested resource is temporarily at a different URL. Browsers do not cache these redirects the same as permanent (301
/308
) redirects, and you should use them when you expect the redirect location to change often, or for the page to return content itself at some point** in the future.
302
- Found: Originally meant to preserve the HTTP method, but in practice most browsers, similar to 301
, changed POST to GET.307
- Temporary Redirect: Serves the same purpose as 302
, but never changes request method automatically.Overall, you should generally prefer 307
and 308
for new applications, and use 301
and 302
mainly for compatibility with older clients or in rare/specific use cases.