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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With