Created
April 5, 2013 17:57
-
-
Save ryanhanwu/5321302 to your computer and use it in GitHub Desktop.
Express JS HTTP + HTTPs server (including auto redirect)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), | |
routes = require('./routes'), | |
upload = require('./routes/upload'), | |
http = require('http'), | |
https = require('https'), | |
fs = require('fs'), | |
path = require('path'), | |
httpApp = express(), | |
app = express(), | |
certPath = "cert"; | |
var httpsOptions = { | |
key: fs.readFileSync(path.join(certPath, "ssl.key")), | |
cert: fs.readFileSync(path.join(certPath, "ssl.crt")) | |
}; | |
httpApp.set('port', process.env.PORT || 80); | |
httpApp.get("*", function (req, res, next) { | |
res.redirect("https://" + req.headers.host + "/" + req.path); | |
}); | |
// all environments | |
app.set('port', process.env.PORT || 443); | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'jade'); | |
app.enable('trust proxy'); | |
app.use(express.favicon()); | |
app.use(express.logger('dev')); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
// development only | |
if('development' == app.get('env')) { | |
app.use(express.errorHandler()); | |
} | |
app.get('/', routes.index); | |
app.post('/upload', upload.s3); | |
http.createServer(httpApp).listen(httpApp.get('port'), function() { | |
console.log('Express HTTP server listening on port ' + httpApp.get('port')); | |
}); | |
https.createServer(httpsOptions, app).listen(app.get('port'), function() { | |
console.log('Express HTTPS server listening on port ' + app.get('port')); | |
}); |
Works very well
Hello everyone,
Im getting this error ERR_TOO_MANY_REDIRECTS
Hello everyone,
Im getting this error ERR_TOO_MANY_REDIRECTS
Some details, please?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ryanhanwu, it could work only if
process.env.PORT
is undefined. Otherwise you tries to listen to the same port two times.Adopting this code for different nonstandard ports, pay attention to:
req.headers.host
contains this port, this is why it is better to usereq.hostname
.