Http to Https redirect does not work on NodeJs in AWS Elastic Beanstalk


Http to Https redirect does not work on NodeJs in AWS Elastic Beanstalk



I created a project using MEAN stack.
In project without redirecting http to https (via app.use("/", httpsRedirect(true)); ) I can access the website without problem.
But after redirecting and deploying I cannot access the website (Timed out).
here code of server.js


const httpsRedirect = require('express-https-redirect');
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const userRoutes = require("./routes/user.routes");
const qrRoutes = require("./routes/qr.routes");
const app = express();
const mongoose = require('mongoose');
const path = require('path');
mongoose
.connect(
"mongodb://username:mypassword@ds217671.mlab.com:17671/mean_qr_scanner"
)
.then(() => {
console.log("Connected to database!");
console.log("3");
})
.catch((er) => {
console.log(er);
});
app.use("/", httpsRedirect(true)); // this cause issue when accessing websit

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use("/", express.static(path.join(__dirname, "angular")));
app.use("/api/user", userRoutes);
app.use("/api/qr", qrRoutes);
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});
module.exports = app;



also tried manual solution for http to https redirect: (same issue)


app.use(function ensureSecure(req, res, next){
if(req.secure){
// OK, continue
return next();
}
// handle port numbers if you need non defaults
res.redirect('https://' + req.hostname + req.url); // express 4.x
});



Strange is AWS BEAN Stalk shows HEALTH is GREEN.
What causes issue? Any idea?
Thanks in advance !




1 Answer
1



To redirect http traffic to https, you should not only configure your application code but Elastic Beanstalk. If your are using Load balancer environment type, you should also concern to configuration of ELB.



Here are some official reference for you:
* Terminating HTTPS on EC2 Instances Running Node.js - https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/https-singleinstance-nodejs.html
* Configuring HTTPS for your Elastic Beanstalk Environment - https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/configuring-https.html






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages