Subdomain in react router

非 Y 不嫁゛ 提交于 2020-06-09 12:19:02

问题


I'd like to setup react router for use with subdomains. I'm unsure where the logic for subdomain proxying should lie.

I want:

roxy.coolestblog.com/profile to route to coolestblog.com/roxy/profile mohammed.coolestblog.com/profile to route to coolestblog.com/mohammed/profile benben.coolestblog.com/profile to route to coolestblog.com/benben/profile

another use case:

en.coolestblog.com/some-article to route to coolestblog.com/en/some-article fr.coolestblog.com/un-article to route to coolestblog.com/fr/un-article es.coolestblog.com/una-article to route to coolestblog.com/es/una-article

I already have it working without the subdomain.

How can I achieve this so it works both on client and server?


回答1:


While the browser history API limits our ability, we can interact directly with window.location in order to accomplish this.

Just before setting up your router, you can modify the URL by doing something like this:

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;
}

Of course, this has its caveats. For instance, if you do not know your host name explicitly, you cannot correctly determine if there is a subdomain or not. It does not make any assumptions about what the following URL should be, but it would be trivial to solve for that.



来源:https://stackoverflow.com/questions/35658252/subdomain-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!