Nowadays SSL certificate / https become general and most important to protect your site and for providing resources with encryption.
here will configure SSL certificate with express js and nodejs
Demo: httpsServer.js
here
-private key file will be .key extension
-certificate file will be .crt extension
-passPhrase is Password of CSR & Private key file
if everything was properly done, you will see a green https bar on the address bar.
if you want to redirect http request to https, follow as per the following demo
We will create another server which runs alongside HTTPS and will redirect to it.
Demo: httpServer.js
Now you have to start two servers
1)httpsServer.js for https request
2)httpServer.js for http request and redirect it to https
here will configure SSL certificate with express js and nodejs
Demo: httpsServer.js
"use strict";
var express = require("express");
var https = require('https');
var fs = require('fs');
var app = express();
sslOptions = {
key: fs.readFileSync(your private key file path),
cert: fs.readFileSync(your certificate file path),
passphrase: passPhrase
};
httpServer = https.createServer(sslOptions, app).listen(443,function (req, res) {
logger.log("info", 'app is listening on ssl...');
});
var express = require("express");
var https = require('https');
var fs = require('fs');
var app = express();
sslOptions = {
key: fs.readFileSync(your private key file path),
cert: fs.readFileSync(your certificate file path),
passphrase: passPhrase
};
httpServer = https.createServer(sslOptions, app).listen(443,function (req, res) {
logger.log("info", 'app is listening on ssl...');
});
here
-private key file will be .key extension
-certificate file will be .crt extension
-passPhrase is Password of CSR & Private key file
if everything was properly done, you will see a green https bar on the address bar.
if you want to redirect http request to https, follow as per the following demo
We will create another server which runs alongside HTTPS and will redirect to it.
Demo: httpServer.js
var express = require('express')
var app = express();
var http = require("http");
app.get('*', function (req, res) {
var httpsEnabledUrl = "https://" + req.headers.host + req.url;
console.log("req.headers.host >> " + httpsEnabledUrl);
res.redirect(httpsEnabledUrl);
});
app.listen(80, function () {
console.log('app is listening on http...');
});
var app = express();
var http = require("http");
app.get('*', function (req, res) {
var httpsEnabledUrl = "https://" + req.headers.host + req.url;
console.log("req.headers.host >> " + httpsEnabledUrl);
res.redirect(httpsEnabledUrl);
});
app.listen(80, function () {
console.log('app is listening on http...');
});
Now you have to start two servers
1)httpsServer.js for https request
2)httpServer.js for http request and redirect it to https
No comments:
Post a Comment