Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 website2.com, but I don't know how. I was trying to use express-force-domain in npm but it makes my URL's crazy and having some redirect loops, I was trying other methods that I find on the web but none succeeds.

my server.js is:

var express = require('express') var app = express();  app.set('port', (process.env.PORT || 80)) app.use(express.static(__dirname + '/public'))  app.get('/', function(request, response) {   response.send('Hello World!') })  app.listen(app.get('port'), function() {   console.log("Node app is running at localhost:" + app.get('port')) }) 

That is the version that works, but without redirects.

like image 666
renatomattos2912 Avatar asked Jun 10 '14 22:06

renatomattos2912


People also ask

What's the method to perform a 301 redirect in JS?

If you need to redirect because the current URL is old, and move the a new URL, it's best to use server-level directive and set the 301 HTTP code to signal search engines that the current URL has permanently moved to the new resource. This can be done via . htaccess if using Apache.

How does redirect work in Express JS?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

How do I redirect a path in node JS?

nodejs1min read In express, we can use the res. redirect() method to redirect a user to the different route. The res. redirect() method takes the path as an argument and redirects the user to that specified path.


2 Answers

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

See Express documentation.

like image 93
Frederic Avatar answered Oct 04 '22 18:10

Frederic


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() 
like image 26
MaxPRafferty Avatar answered Oct 04 '22 16:10

MaxPRafferty