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

前端 未结 3 1961
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 00:40

I have a static site, a simple single page layout that I deploy in Dokku. I need to make a redirect (301) from www to non www and from *.website1.com to w

相关标签:
3条回答
  • 2020-12-10 01:04

    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()
    
    0 讨论(0)
  • 2020-12-10 01:13
    res.redirect(301, 'http://yourotherdomain.com' + req.path)
    

    See Express documentation.

    0 讨论(0)
  • 2020-12-10 01:22

    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

    0 讨论(0)
提交回复
热议问题