Skip to content

Instantly share code, notes, and snippets.

@nuintun
Last active May 13, 2019 06:27
Show Gist options
  • Save nuintun/9951781 to your computer and use it in GitHub Desktop.
Save nuintun/9951781 to your computer and use it in GitHub Desktop.
NodeJS实现多域名解析
引用vhost.js,脚本代码如下:
module.exports = function vhost(hostname, server){
  if (!hostname) throw new Error('vhost hostname required');
  if (!server) throw new Error('vhost server required');
  
  var regexp = new RegExp(
    '^' + hostname.replace(/[^*\w]/g, '\\$&').replace(/[*]/g, '(?:.*?)') + '$',
    'i'
  );
  
  if (server.onvhost) server.onvhost(hostname);
  
  return function vhost(req, res, next){
    if (!req.headers.host) return next();
    
    var host = req.headers.host.split(':')[0];
    
    if (!regexp.test(host)) return next();
    if ('function' == typeof server) return server(req, res, next);
    
    server.emit('request', req, res);
  };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment