Giter Site home page Giter Site logo

vhost's Introduction

vhost

NPM Version NPM Downloads Build Status Test Coverage

Install

$ npm install vhost

API

var vhost = require('vhost')

vhost(hostname, handle)

Create a new middleware function to hand off request to handle when the incoming host for the request matches hostname. The function is called as handle(req, res, next), like a standard middleware.

hostname can be a string or a RegExp object. When hostname is a string it can contain * to match 1 or more characters in that section of the hostname. When hostname is a RegExp, it will be forced to case-insensitive (since hostnames are) and will be forced to match based on the start and end of the hostname.

When host is matched and the request is sent down to a vhost handler, the req.vhost property will be populated with an object. This object will have numeric properties corresponding to each wildcard (or capture group if RegExp object provided) and the hostname that was matched.

var connect = require('connect')
var vhost = require('vhost')
var app = connect()

app.use(vhost('*.*.example.com', function handle (req, res, next) {
  // for match of "foo.bar.example.com:8080" against "*.*.example.com":
  console.dir(req.vhost.host) // => 'foo.bar.example.com:8080'
  console.dir(req.vhost.hostname) // => 'foo.bar.example.com'
  console.dir(req.vhost.length) // => 2
  console.dir(req.vhost[0]) // => 'foo'
  console.dir(req.vhost[1]) // => 'bar'
}))

Examples

using with connect for static serving

var connect = require('connect')
var serveStatic = require('serve-static')
var vhost = require('vhost')

var mailapp = connect()

// add middlewares to mailapp for mail.example.com

// create app to serve static files on subdomain
var staticapp = connect()
staticapp.use(serveStatic('public'))

// create main app
var app = connect()

// add vhost routing to main app for mail
app.use(vhost('mail.example.com', mailapp))

// route static assets for "assets-*" subdomain to get
// around max host connections limit on browsers
app.use(vhost('assets-*.example.com', staticapp))

// add middlewares and main usage to app

app.listen(3000)

using with connect for user subdomains

var connect = require('connect')
var serveStatic = require('serve-static')
var vhost = require('vhost')

var mainapp = connect()

// add middlewares to mainapp for the main web site

// create app that will server user content from public/{username}/
var userapp = connect()

userapp.use(function (req, res, next) {
  var username = req.vhost[0] // username is the "*"

  // pretend request was for /{username}/* for file serving
  req.originalUrl = req.url
  req.url = '/' + username + req.url

  next()
})
userapp.use(serveStatic('public'))

// create main app
var app = connect()

// add vhost routing for main app
app.use(vhost('userpages.local', mainapp))
app.use(vhost('www.userpages.local', mainapp))

// listen on all subdomains for user pages
app.use(vhost('*.userpages.local', userapp))

app.listen(3000)

using with any generic request handler

var connect = require('connect')
var http = require('http')
var vhost = require('vhost')

// create main app
var app = connect()

app.use(vhost('mail.example.com', function (req, res) {
  // handle req + res belonging to mail.example.com
  res.setHeader('Content-Type', 'text/plain')
  res.end('hello from mail!')
}))

// an external api server in any framework
var httpServer = http.createServer(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.end('hello from the api!')
})

app.use(vhost('api.example.com', function (req, res) {
  // handle req + res belonging to api.example.com
  // pass the request to a standard Node.js HTTP server
  httpServer.emit('request', req, res)
}))

app.listen(3000)

License

MIT

vhost's People

Contributors

dougwilson avatar jonathanong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vhost's Issues

req.vhost is undefined

This is my main code, but I get req.vhost is undefined, any idea what can cause it?

app.use(function(req, res, next){
console.log(req.vhost)
  var username = req.vhost[0] // username is the "*"
  console.log(username)
 
  // pretend request was for /{username}/* for file serving
  req.originalUrl = req.url;
  console.log('req '+ req.originalUrl)
  req.url = '/' + username + req.url
  console.log(req.url)


  next()
})

app.use(vhost('*.myapp.local', indexRouter))

if I delete the console logs in the middleware the right route is rendered, but it is important to have access to the req.vhost[0] to render dynamic data based on the subdomain the user is typing

HTTPS Server

Hiya, I was looking around in the issues and I saw #23. I wanted to add, is there a way we can have a different certificate for certain domains? I was looking into the vhttps module but it appears it doesn't support the "ca" object field for the SSL, as it's not working correctly for me. I'd love some sort of support for this module natively. Thanks!

Basically vhttps doesnt have an option to send the correct Intermediate Certificates, therefore its saying the connection isn't secure as it cannot verify issuer.

Using express vhost behind a reverse proxy

I'm using express vhost behind a reverse proxy and i want to use this module based on the x-forwarded-host header as opposed to the host header that is hardcoded here:

vhost/index.js

Line 77 in 12565d1

var host = req.headers.host

Express 4 supports this by accessing req.hostname directly: http://expressjs.com/en/4x/api.html#req.hostname

Express 3 supports this at req.host:
http://expressjs.com/en/3x/api.html#req.host

Is this module still intended to support express v3? Would you accept a pull request that replaces:

vhost/index.js

Line 77 in 12565d1

var host = req.headers.host

with:

var host = req.hostname || req.host

to keep support with both express v3 and v4.

EDIT:
I've just re-read the readme again and this would be the only part of this module which adds a direct express dependency. Maybe the code could be:

var host = req.hostname || req.host || req.headers.host

To support express 3/4 and connect servers.

How to have *.domain.com and domain.com work together?

Here's my problem, I hope someone can help.

I'm trying to write an app which, depending on the subdomain accessed, proxifies the user to another webapp listening to each a different port.

Exemple :

  • abcd.domain.com redirects to an app on port 1200
  • efgh.domain.com redirects to an app on port 1201
  • etc.

There's also a React app on domain.com (without any subdomain).

My problem lies in the fact that it doesn't work at all.

My current code is like this

app.use(vhost(`${conf.Frontend.Host}`, mainApp));
app.use(vhost(`*.${conf.Frontend.Host}`, getKMRoom), proxy(redirectKMRoom, {
		memoizeHost: false
	}));

...

unction getKMRoom(req, res, next) {
	const instance = getInstanceRoom(req.vhost[0]);
	if (!instance) {
		res.status(404).send('No room exists by this name');
	} else {
		req.KMAppPort = instance.port;
		next();
	}
}

function redirectKMRoom(req) {
	return `http://localhost:${req.KMAppPort}`;
}

In this configuration, when I access domain.com I get my react app (mainApp is called) but not with aaaa.domain.com. It never goes through and isn't picked by any route. Actually, getKMRoom isn't even called.

I'd like to understand what I'm doing wrong there, if anyone knows?

Thanks in advance.

Stop test server

Hello,

I had to add this to stop properly tests:

--- a/test/test.js
+++ b/test/test.js
@@ -207,6 +207,7 @@
       .get('/')
       .set('Host', 'user-bob.foo.com:8080')
       .expect(200, '[["0","bob"],["1","foo"],["host","user-bob.foo.com:8080"],["hostname","user-bob.foo.com"],["length",2]]', done)
+      setTimeout(app.close,2000)
     })
   })
 })

Vhost's ending in wildcard do not match. Version 3.0.2

Vhost will not match if the last char is *. making it harder to develop locally.

Ex:

const express = require('express')
const vhost = require('vhost')

// Configuration
const PORT = 3000;
const HOST = "localhost";

const app = express()
const ok = express()
const fail = express()

ok.use('', (req, res, next) => {
	res.send('ok found\n')
})

fail.use('', (req, res, next) => {
	res.send('fail found\n')
})

app.use(vhost('ok.lvh.me', ok)) //lvh.me will always resolv to 127.0.0.1
app.use(vhost('fail.*', fail))  //This will not match
app.use('', (req, res, next) => {
	res.status(404).send('Vhost Not found\n')
})


app.listen(PORT, HOST, () => {
   console.log(`Starting Proxy at ${HOST}:${PORT}`);
});

Calling the server will have the following results:
$ curl 'http://ok.lvh.me:3000/' ok found
$ curl 'http://fail.lvh.me:3000/' Vhost Not found

vhost for other web frameworks.

Hello, there. I'm sorry if it has already been asked, but I don't find it. My primary web server is based on express, but I want to manage my API with Hapi.js and serve it at api.example.com. So my question is: "can I use vhost for managing web frameworks other than connect, express, etc. by architecture?" Thanks :)

each vhost https support

how to set ssl cert for each hostname

just like this :

app.use(
  vhost('a.lo.shynome.com',{ cert:'a.lo.shynome.com_bundle.crt',key:'a.lo.shynome.com.crt' },require('./a')),
  vhost('b.lo.shynome.com',{ cert:'b.lo.shynome.com_bundle.crt',key:'b.lo.shynome.com.crt' },require('./b')),
  (req,res)=>res.send('none catch'),
)

Can this be realized?

if you visit https://a.lo.shynome.com/ , Google Chrome will tip u it's unsafe

this is code https://github.com/shynome/vhost-test

Subdomains in localhost

This is our code

var express = require('express');
var vhost = require('vhost');

var app = express();
app.use(vhost('mail.example.com', function(req, res){
  res.send('I am mail.example.com');
}));
app.use(vhost('*.mail.example.com', function(req, res){
  res.send('I am *.example.com')
}));
app.listen(3000, function(){
  console.log('Listening at port 3000');
});

Our /etc/hosts file contains this line, so that we can start the application in our localhost

127.0.0.1       mail.example.com

When we hit the url 'http://mail.example.com:3000', we do get the response 'I am mail.example.com'.
But when we hit the url 'http://a.mail.example.com:3000', we are getting the 'Server not found' response.
Am I doing anything wrong here?

Issues with SEO

Hello.
Although i think my question may sound stupid to you, but i don't know what to do.
I've been using this module with the project i was working on (a month ago), currently it's live. Actually there is no issue with your module, but i got a complaint saying that website absolutely is not getting indexed, and that company's seo experts are not finding any issues in search console and so on. I just thought - can it be because of this? I mean the master website - domain.com is indexed (partly), and some images of the subdomains of it (created with this package) got some of the images indexed (although the website address in google is not https://sub.domain.com, it's https://domain.com), but other then that nothing else seems to be indexed.

Just want to make sure - can it be because of using virtual hosts, or should i look for the problem somewhere else.

vhost for multiple domain

For example I have 3 domains called abc.com, def.com and ghi.com

I want the vhost to be able to serve *.abc.com, *.def.com and *.ghi.com, but I want to do it automatically means that the domains can be added dynamically.

Is there any way to do it?

Removing vhosts

Was looking at removing vhosts at runtime the other day. There doesn't seem to be a nice way to identify the hostnames that are added to the routing stack; so messing with router._stack quickly becomes a pain. I was thinking that we could perhaps add an identifier - such as hostname - to the middleware key or similar so it can be identified (and then spliced from router._stack). Thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.