react-router中的子域

IT技术 reactjs subdomain react-router
2021-04-27 15:43:04

我想设置react-router以用于子域。我不确定子域代理的逻辑应该在哪里。

我想:

roxy.coolestblog.com/profile到路由到coolestblog.com/roxy/profile mohammed.coolestblog.com/profile路由coolestblog.com/mohammed/profile benben.coolestblog.com/profile到路由到coolestblog.com/benben/profile

另一个用例:

en.coolestblog.com/some-article到路由到coolestblog.com/en/some-article fr.coolestblog.com/un-article路由coolestblog.com/fr/un-article es.coolestblog.com/una-article到路由到coolestblog.com/es/una-article

我已经让它在没有子域的情况下工作。

我怎样才能做到这一点,以便它在客户端和服务器上都能工作?

1个回答

虽然浏览器历史 API 限制了我们的能力,但我们可以直接与之交互window.location以实现这一目标。

在设置路由器之前,您可以通过执行以下操作来修改 URL:

let host = window.location.host;
let protocol = window.location.protocol;
let parts = host.split(".");
let subdomain = "";
// If we get more than 3 parts, then we have a subdomain
// INFO: This could be 4, if you have a co.uk TLD or something like that.
if (parts.length >= 3) {
  subdomain = parts[0];
  // Remove the subdomain from the parts list
  parts.splice(0, 1);
  // Set the location to the new url
  window.location = protocol + "//" + parts.join(".") + "/" + subdomain;
}

当然,这有其警告。例如,如果您不明确知道您的主机名,则无法正确确定是否存在子域。它不会对以下 URL 应该是什么做出任何假设,但解决这个问题是微不足道的。