gpt4 book ai didi

node.js - 在express js和node js上创建动态子域

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:53 24 4
gpt4 key购买 nike

我正在尝试制作一个网站,当用户注册时,他将拥有 url > username.mydomain.com,我尝试了多种方法,从 vcap.me 等,以及如何创建动态子域例如简单易行,

最佳答案

// Use below code to get your subdomain name
// get your dynamic subdomain

app.use((req, res, next) => {
if (!req.subdomains.length || req.subdomains.slice(-1)[0] === 'www') return next();
// otherwise we have subdomain here
var subdomain = req.subdomains.slice(-1)[0];
// keep it
req.subdomain = subdomain;
next();
});


// conditional render a page
app.get('/', (req, res) => {
// no subdomain
if (!req.subdomain) {
// render home page
// mydomain.com
res.render('home');
} else {
// render subdomain specific page
// mypage.mydomain.com
res.render('mypage');
} // you can extend this else logic to render the different subdomain specific page
});


Note: to test this locally. you can use Nginx reverse proxy to forward your test url req to your local server and do not forget to point your test url to your local host 127.0.0.1 in your hosts file of your machine

关于node.js - 在express js和node js上创建动态子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43148219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com