Junior — Middle
Can you explain what redirect means in the HTTP protocol and how it works?
sobes.tech AI
Answer from AI
HTTP redirect is a mechanism where the server informs the client that the requested resource is located at a different URL, and the client should make a new request to that address.
How it works:
- The client sends an HTTP request to the server.
- The server responds with a status code from the 3xx group (e.g., 301, 302, 307) and a
Locationheader indicating the new URL. - The client automatically or manually makes a new request to the specified address.
Example of a server response:
HTTP/1.1 302 Found
Location: https://example.com/newpage
In Node.js with Express, you can perform a redirect like this:
app.get('/old-page', (req, res) => {
res.redirect(301, '/new-page');
});
This is useful for changing website structure, load balancing, or resource migration without losing users.