如何在node.js中为用户创建子域 [英] How to create subdomain for user in node.js

查看:37
本文介绍了如何在node.js中为用户创建子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序的username.domain.com上共享一些用户信息.用户创建帐户后,子域应该可用.

我发现在这种情况下可能有用的不错的模块:快速子域

如何使用该模块正确执行操作?也许此模块不是那么有用,所以我应该使用哪个模块?

正如我在OP注释中提到的,在Node前面使用Nginx Web服务器将是一个很好的选择,因为这是侦听80端口的一种安全方法.您还可以使用Nginx更有效地提供静态文件(脚本,样式,图像,字体等),并在一台服务器中具有多个站点.

对于您的问题,使用Nginx,您可以同时监听 example.com 及其所有子域,然后将子域作为自定义请求标头( X-Subdomain ).

example.com.conf:

 服务器{听*:80;server_name example.com * .example.com;设置$ subdomain";如果($ host〜^(.*)\.example \ .com $){设置$ subdomain $ 1;}地点/{proxy_pass http://127.0.0.1:3000;proxy_set_header X-Subdomain $ subdomain;}} 

app.js:

  var express = require('express');var app = express();app.get('/',function(req,res){res.end('Subdomain:'+ req.headers ['x-subdomain']);});app.listen(3000); 

这是一起使用Nginx和Node的简短示例.您可以在此处看到更多详细的示例.

I'd like to share some user information at username.domain.com at my application. Subdomain should be available after user create his account.

I have found nice module that could be useful in that case: Express Subdomain

How can I do it properly using that module? Maybe this module isn't so useful so which one should I use?

解决方案

As I mentioned in OP comments, using Nginx webserver in front of Node would be very good option, since this is a secure way to listen 80 port. You can also serve static files (scripts, styles, images, fonts, etc.) more efficiently, as well as have multiple sites within a single server, with Nginx.

As for your question, with Nginx, you can listen both example.com and all its subdomains, and then pass subdomain to Node as a custom request header (X-Subdomain).

example.com.conf:

server {
    listen          *:80;
    server_name     example.com   *.example.com;

    set $subdomain "";
    if ($host ~ ^(.*)\.example\.com$) {
        set $subdomain $1;
    }

    location / {
        proxy_pass          http://127.0.0.1:3000;
        proxy_set_header    X-Subdomain     $subdomain;
    }
}

app.js:

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

app.get('/', function(req, res) {
    res.end('Subdomain: ' + req.headers['x-subdomain']);
});

app.listen(3000);

This is a brief example of using Nginx and Node together. You can see more detailed example with explanation here.

这篇关于如何在node.js中为用户创建子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆