2 expressjs snippets
Snippets are tiny notes I've collected for easy reference.
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):
JavaScript:
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();
}
});
CoffeeScript:
app.all '/*', (req, res, next)->
if /^www\./.test req.headers.host
res.redirect "#{req.protocol}://#{req.headers.host.replace(/^www\./,'')}#{req.url}",301
else
next()
Published 13 Mar 2014
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.
JavaScript:
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:
http = require 'http'
express = require 'express'
HTTP_PORT = 80
HTTPS_PORT = 443
http_app = express()
http_app.set 'port', HTTP_PORT
http_app.all '/*', (req, res, next)->
if /^http$/.test req.protocol
host = req.headers.host.replace /:[0-9]+$/g, "" # strip the port # if any
if HTTPS_PORT? and HTTPS_PORT isnt 443
res.redirect "https://#{host}:#{HTTPS_PORT}#{req.url}", 301
else
res.redirect "https://#{host}#{req.url}", 301
else
next()
http.createServer(http_app).listen(HTTP_PORT).on 'listening',()->
console.log "HTTP to HTTPS redirect app launched."
Published 13 Mar 2014
Snippets are tiny notes I've collected for easy reference.