Blog>
Snippets

Redirects and URL Rewriting

Show how to use middleware to perform redirects or rewrite URLs based on certain route patterns.
const express = require('express');
const app = express();

// Redirect from /old-path to /new-path
app.get('/old-path', (req, res) => {
  res.redirect(301, '/new-path');
});

// URL Rewriting: Rewrite /user/:id to /profile/:id
app.use('/user/:id', (req, res, next) => {
  const { id } = req.params;
  req.url = `/profile/${id}`;
  next();
});

// This route will handle the rewritten URL
app.get('/profile/:id', (req, res) => {
  res.send(`Profile page for user with ID ${req.params.id}`);
});

// Start server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
This Express.js middleware example performs a 301 redirect from '/old-path' to '/new-path'. It also rewrites the URL from '/user/:id' to '/profile/:id'. Finally, it starts an Express server listening on port 3000.