Reputation: 63
I am using NodeJS, specifically, I am using the tutorial code from node-js-getting-started. So I have a custom domain, but the default heroku domain is also active, and I would like to have the custom domain be the only one in use. Heroku said to do this.
Your app’s Heroku domain always remains active, even if you set up a custom domain. If you want users to use the custom domain exclusively, your app should send HTTP status 301 Moved Permanently to tell web browsers to use the custom domain. The Host HTTP request header field will show which domain the user is trying to access; send a redirect if that field is example.herokuapp.com.
I don't really understand how to do this. I'm guessing I have to change something in the index.js file.
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
express()
.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`))
Upvotes: 1
Views: 1050
Reputation: 683
If the route is "/" or actually any route you should redirect it to your domain with code 301.
Try something like this.
var express = require('express')
var app = express()
self.app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^herokuapp\..*/i)) {
res.redirect(301, "http://www." + host + req.url);
} else {
next();
}
});
Upvotes: 0