Reputation: 827
I currently have a react/node app sitting in an EC2 ubuntu instance at /home/ubuntu. The server is an https server listening on port 443. When I hit my Public DNS, it only appears when I prepend https:// before my dns. It works as expected(without it, it defaults to port 80 and the app doesn't show, which is expected).
I have a certificate generated by amazon and amazon certificate manager. How do I redirect all traffic from port 80 to port 443 and integrate my amazon certificate into my instance?
Upvotes: 0
Views: 4517
Reputation: 827
So, thanks to Adiii, he pointed me in the right direction. What I did was create an Elastic IP for my instance(really easy), then I put my instance behind an elastic load balancer(amazon ELB)(also easy), I set my port in ELB from 443 to 443, 80 to 80. I added my certificate on the 443 to 443 port redirect.
I already had my instance configured and app running, so I referenced /index.html for the health check to get it coming into service with the ELB. I had my app running on port 443. I added an http_redirect.js server file listening on port 80.
const express = require('express');
const http = require('http');
const app = express();
// set up a route to redirect http to https
app.get('*', function(req, res) {
res.redirect('https://' + req.headers.host + req.url);
})
http.createServer(app).listen(80, () => {
console.log('redirect-server up and running on port 80');
});
It just redirects to port 443 for https. With this, I was able to use my free certificate from AWS and also redirect from http to https using express/node.
Upvotes: 1
Reputation: 60114
You can try two option.
I will prefer ALB as you do not need expose port at the instance level and also you will not manage any proxy at the instance.
If you are using ALB, you can redirect to https from LB rule. A rule has to have a condition and an action. Since we want to redirect all traffic that comes in on port 80 to the same URI, just with HTTPS instead, our condition should be simply “all”. Unfortunately you can’t just put a single asterisk in for the condition, the closest I’ve been able to come up with is
*.example.com
, wherexample.com
is whatever your domain is.
If you are not using ALB, then you can try Nginx.
This will redirect all
server {
listen 80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
This will redirect the specific site.
server {
listen 80;
server_name example.com;
return 301 https://example.com$request_uri;
}
Another clarification from your question
How to integrate my amazon certificate into my instance?
No, You can not use AWS certificate within EC2 instance, you need to place LB on the top of Instance to use AWS certificate.
Upvotes: 1
Reputation: 1577
You need to redirect HTTP to HTTPS in your node app. There are many examples on how to do this online, for example: Automatic HTTPS connection/redirect with node.js/express
Upvotes: 1