Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 334 Vote(s) - 3.55 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make a redirect (301) in Node.js / Express?

#1
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.

Reply

#2
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
Reply

#3
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()
Reply

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

See [Express documentation][1].


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through