Junior
How does HTTP redirect work?
sobes.tech AI
Answer from AI
Redirect in HTTP is a mechanism that redirects the client (browser) from one URL to another.
It works as follows:
- The client sends an HTTP request to the original URL.
- The server receives the request and instead of sending a page for the original URL, sends an HTTP response with a redirect status code (e.g.,
301- permanent,302- temporary). - The server also includes a
Locationheader with the new URL to redirect to. - The browser, upon receiving the redirect status code and
Locationheader, automatically sends a new HTTP request to the URL specified inLocation.
Examples of redirect status codes:
| Status code | Description |
|---|---|
301 |
Moved Permanently |
302 |
Found |
303 |
See Other |
307 |
Temporary Redirect |
308 |
Permanent Redirect |
Example of an HTTP redirect response:
HTTP/1.1 301 Moved Permanently
Location: https://new-example.com/new/path/
Content-Length: 0
In Node.js, redirect is usually implemented by setting the appropriate status code and Location header in the response object.
Example in Express.js:
// In route handler
app.get('/old-path', (req, res) => {
res.redirect(301, '/new-path'); // Redirect with 301 to /new-path
});
Example in plain Node.js:
// In http server
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/old-path') {
res.writeHead(302, { 'Location': '/new-path' }); // Temporary redirect
res.end();
} else {
// Handle other requests
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!');
}
});
server.listen(3000);
This mechanism is essential for guiding clients to the correct resource, handling URL changes, or implementing load balancing and other server-side logic.