pedro-pinho
8/20/2018 - 5:39 PM

NodeJS

/*Redirect www.example.com to example.com in Node.js and Express.js
To redirect all paths on the "www" version of a hostname to the "non-www" (domain only) version using Express.js (or Connect):
*/
app.all('/*', function(req, res, next) {
 if(/^www\./.test(req.headers.host)) {
  res.redirect(req.protocol + '://' + req.headers.host.replace(/^www\./,'') + req.url,301);
 } else {
  next();
 }
});
var https      = require("https");
var fs         = require("fs");
var key_file   = "/path/to/file.pem";
var cert_file  = "/path/to/file.crt";
var passphrase = "this is optional";
var config     = {
  key: fs.readFileSync(key_file),
 cert: fs.readFileSync(cert_file)
};
if(passphrase) {
  config.passphrase = passphrase;
}

https.createServer(config,app).listen(443);
/*
Where /path/to/file.pem is the path to a file containing an RSA key, generated (for example) by:

openssl genrsa 1024 > /path/to/file.pem
and /path/to/file.crt is the path to a file containing an SSL certificate, generated (for example) by:

openssl req -new -key /path/to/file.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey /path/to/file.pem -out /path/to/file.crt
*/
/*
Redirect http: to https: in Node.js and Express.js
To redirect all HTTP requests to the equivalent HTTPS requests using Express.js
you can create a simple Express instance that listens on the HTTP port and performs the redirect.
*/
var http       = require('http');
var express    = require('express');
var HTTP_PORT  = 80;
var HTTPS_PORT = 443;

var http_app = express();
http_app.set('port', HTTP_PORT);

http_app.all('/*', function(req, res, next) {
  if (/^http$/.test(req.protocol)) {
    var host = req.headers.host.replace(/:[0-9]+$/g, ""); // strip the port # if any
    if ((HTTPS_PORT != null) && HTTPS_PORT !== 443) {
      return res.redirect("https://" + host + ":" + HTTPS_PORT + req.url, 301);
    } else {
      return res.redirect("https://" + host + req.url, 301);
    }
  } else {
    return next();
  }
});

http.createServer(http_app).listen(HTTP_PORT).on('listening', function() {
  return console.log("HTTP to HTTPS redirect app launched.");
});
CoffeeScript: