How to make a redirect (301) in Node.js / Express? How to make a redirect (301) in Node.js / Express? express express

How to make a redirect (301) in Node.js / Express?


res.redirect(301, 'http://yourotherdomain.com' + req.path)

See Express documentation.


To anyone arriving here from Google, while @frederic's answer is still what is recommended by the express docs, the response.send(status, body) style has been deprecated and will generate a warning (I am on express 4.13.4 at time of writing), and more importantly I found that it no longer produced the desired result when redirecting.

As @Markasoftware mentioned, to achieve an automatically followed 301, you need to set the location header to the url you want. The request body can be empty:

   response.set('location', 'https://my.redirect.location');   response.status(301).send()


As far as I understand it, to set an HTTP 301 code, you would set the response code to be 301 and then set the Location header to whatever url you want it to redirect to. I don't think this is the preferred way to do www to non-www urls though