Skip to content

Commit

Permalink
Add support for reverse proxies by checking req.hostname or req.host. F…
Browse files Browse the repository at this point in the history
…ixes expressjs#20

This is so that the module works when express has `trust proxy` enabled
and the `Host` header is expected to come from `X-Forwarded-Host`
  • Loading branch information
Dom Harrington committed Dec 7, 2016
1 parent 12565d1 commit 5f5a569
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ function vhost (hostname, handle) {
*/

function hostnameof (req) {
var host = req.headers.host
var host = req.hostname || // express v4
req.host || // express v3
req.headers.host // http

if (!host) {
return
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"license": "MIT",
"repository": "expressjs/vhost",
"devDependencies": {
"connect": "^3.5.0",
"eslint": "2.11.1",
"eslint-config-standard": "5.3.1",
"eslint-plugin-promise": "1.3.1",
Expand Down
41 changes: 41 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
var assert = require('assert')
var http = require('http')
var request = require('supertest')
var connect = require('connect')
var vhost = require('..')

describe('vhost(hostname, server)', function () {
Expand All @@ -22,6 +23,46 @@ describe('vhost(hostname, server)', function () {
.expect(200, 'tobi', done)
})

it('should route by `req.hostname` (express v4)', function (done) {
var app = connect()

app.use(function (req, res, next) {
req.hostname = 'anotherhost.com'
return next()
})

app.use(vhost('anotherhost.com', anotherhost))
app.use(vhost('loki.com', loki))

function anotherhost (req, res) { res.end('anotherhost') }
function loki (req, res) { res.end('loki') }

request(app)
.get('/')
.set('Host', 'tobi.com')
.expect(200, 'anotherhost', done)
})

it('should route by `req.host` (express v3)', function (done) {
var app = connect()

app.use(function (req, res, next) {
req.host = 'anotherhost.com'
return next()
})

app.use(vhost('anotherhost.com', anotherhost))
app.use(vhost('loki.com', loki))

function anotherhost (req, res) { res.end('anotherhost') }
function loki (req, res) { res.end('loki') }

request(app)
.get('/')
.set('Host', 'tobi.com')
.expect(200, 'anotherhost', done)
})

it('should ignore port in Host', function (done) {
var app = createServer('tobi.com', function (req, res) {
res.end('tobi')
Expand Down

0 comments on commit 5f5a569

Please sign in to comment.