一个 Next.js 路由中的两个不同子域 [英] Two different subdomains in one Next.js routing
问题描述
我想使用 Next.js (React.js 和 React-路由器).会有两个空格.一个前端用于用户,另一个用于所有者,允许他们管理所有用户.我想将两个区域分成两个子域,如下所示:
I want to build a new platform using Next.js (React.js and React-router). There will be a two spaces. One front-end for users and one for the owner to allow them manage all users. I want to split both areas into two subdomains, like this:
front.domain.companel.domain.com
front.domain.com panel.domain.com
React-router 不支持子域路由,所以我尝试寻找另一种方法.我发现了类似的东西,但我不确定这是我想要的.请指教.
React-router does not support sub-domain routing, so I tried to find another approach. I found something like that, but I am not sure that this is what I want. Please advice.
<BrowserRouter>
<Route path="/" render={props => {
const [subdomain] = window.location.hostname.split('.');
if (subdomain === 'panel') return <PanelLayout {...props}/>;
return <FrontLayout {...props}/>;
}}/>
</BrowserRouter>
推荐答案
出于多种原因,您不能在子域之间拆分 1 个 Next.js 应用程序.根据经验,我有一个类似的要求(3 个领域),我从一个应用程序开始,将其拆分为 3 个(使用子路径)
You can't split 1 Next.js app between sub-domains for several reasons. From an experience, I had a similar requirement (3 areas) I started with one app split into 3 (using sub paths)
- 资产(css、js 库)在区域"之间泄漏.
- 一个包含 3 个区域的大应用意味着,每次更改都需要重新部署所有区域(一个大的可部署区域)
- 构建时间,构建 3 个区域会更长.
- 每个区域可能会引入不同的需求,例如,管理区域的 UI 组件,但前端"的自定义 ui 组件需要区域、授权、翻译等等
最终得到 3 个独立的 Next.js 应用程序,这些应用程序在 yarn 工作区内部进行管理并由特定区域部署.
Ended up with 3 separate Next.js apps which managed inside yarn workspaces and get deployed by a specific area.
在我解释了我的经验之后,您可以使用反向代理实现设置,例如 nginx 将子域映射到下一个应用中的子路径.
After I've explained my experience, you can achieve a setup with a reverse-proxy such as nginx to map sub-domain to subpath in your next app.
假设您有 3 个区域,前台、管理员、用户.
Let's say you have 3 areas, front, admin, users.
www.domain.com/some-page
=>应该映射到 localhost:3000/front/some-page
.users.domain.com/some-page
=>应该映射到 localhost:3000/users/some-page
.admin.domain.com/some-page
=>应该映射到 localhost:3000/admin/some-page
.
www.domain.com/some-page
=> should be mapped to localhost:3000/front/some-page
.
users.domain.com/some-page
=> should be mapped to localhost:3000/users/some-page
.
admin.domain.com/some-page
=> should be mapped to localhost:3000/admin/some-page
.
// www.domain.com.conf
server {
listen 80;
server_name www.domain.com;
access_log /var/log/nginx/access.log main;
root html;
location / {
proxy_pass http://127.0.0.1:3000/front/; // <-- the last slash is important
}
}
// users.domain.com.conf
server {
listen 80;
server_name users.domain.com;
access_log /var/log/nginx/access.log main;
root html;
location / {
proxy_pass http://127.0.0.1:3000/users/; // <-- the last slash is important
}
}
注意
- 您还需要重写静态资产.
这篇关于一个 Next.js 路由中的两个不同子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!