Sobes.tech
Junior

How does HTTP redirect work?

sobes.tech AI

Answer from AI

HTTP redirection is a mechanism by which a web server informs the client (browser) that the requested resource has been moved to another URL. The client then automatically makes a new request to the specified address. The main HTTP status codes for redirection:

  • 301 Moved Permanently: The resource has been permanently moved. The client should use the new URL for future requests. Search engines pass link equity.
  • 302 Found (formerly "Moved Temporarily"): The resource is temporarily available at a different address. The client should continue to use the original URL for future requests. Search engines typically do not pass link equity.
  • 303 See Other: The response to a request, usually POST, instructs the client to get the resource at another URL using the GET method.
  • 307 Temporary Redirect: Similar to 302, but does not allow changing the HTTP method (e.g., POST remains POST).
  • 308 Permanent Redirect: Similar to 301, but does not allow changing the HTTP method.

Process:

  1. The client sends a request to URL A.
  2. The server, instead of sending the content of URL A, returns an HTTP response with a redirection status code (e.g., 301) and a Location header containing the new URL (URL B).
  3. The client (browser) automatically extracts URL B from the Location header and sends a new request to URL B.
  4. The server processes the request to URL B and returns the appropriate response (e.g., 200 OK).

In Node.js with Express.js, redirection is performed using the res.redirect() method:

// Example of 302 redirect
app.get('/old-path', (req, res) => {
  res.redirect('/new-path'); // Defaults to 302
});

// Example of 301 redirect
app.get('/legacy-path', (req, res) => {
  res.redirect(301, '/modern-path');
});

Headers:

HTTP Header Value Description
Location /new-path or https://example.com/ Indicates the new URL for redirection.

Redirections are used to correct typos in URLs, move websites, enforce HTTPS, merge pages, and URL shortening.

How does HTTP redirect work? — Node.js - sobes.tech