Check your web redirects and HTTP responses
Redirects with Node.js / Express
Node.js is a server-side JavaScript runtime, often used with the Express framework to build web applications. Redirects are handled directly in the code using the res.redirect() method.
301 (permanent) redirect with Express
Redirect a specific page:
app.get('/old-page', (req, res) => {
res.redirect(301, 'https://www.example.net/new-page');
});
Redirect all URLs with a given prefix:
app.get('/old-directory/*', (req, res) => {
const newPath = req.path.replace('/old-directory', '/new-directory');
res.redirect(301, newPath);
});
302 (temporary) redirect with Express
res.redirect() sends a 302 code by default:
app.get('/temp-page', (req, res) => {
res.redirect('https://www.example.net/destination-page');
});
Force HTTPS (middleware)
Place before other routes to force all requests to HTTPS:
app.use((req, res, next) => {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(301, 'https://' + req.headers.host + req.url);
}
next();
});
Note: x-forwarded-proto is the header sent by proxies and load balancers (Nginx, Heroku, AWS…). On a direct server without a proxy, use req.secure instead.
Complete example
const express = require('express');
const app = express();
// Force HTTPS
app.use((req, res, next) => {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(301, 'https://' + req.headers.host + req.url);
}
next();
});
// 301 redirect
app.get('/old-page', (req, res) => {
res.redirect(301, '/new-page');
});
app.listen(3000);