简体   繁体   English

使用Javascript重定向到台式机/移动版的相应页面

[英]Redirecting to respective page of desktop/mobile version using Javascript

I have different domain names for mobile ( http://m.mydomain.com ) and desktop ( http://web.mydomain.com ) users. 对于移动( http://m.mydomain.com )和台式机( http://web.mydomain.com )用户,我具有不同的域名。 I am currently using following Javascript code to redirect my desktop users accessing mobile URLs to desktop URLs. 我目前正在使用以下Javascript代码将访问移动URL的桌面用户重定向到桌面URL。

 <script> var isDesktop = { Windows: function() { return navigator.platform.match('Win32|Win16|Win64|WinCE|Windows'); }, Mac: function() { return navigator.platform.match('MacIntel|Macintosh|MacPPC|Mac68K'); }, any: function() { return (isDesktop.Windows() || isDesktop.Mac()); } }; if (isDesktop.any()){ window.location='http://web.mydomain.com'; } </script> 

But the issue is: The user is redirected to main-page ( http://web.mydomain.com ) no matter on which page he is. 但是问题是:无论用户位于哪个页面上,都将其重定向到主页( http://web.mydomain.com )。 I want to redirect them to the respective page. 我想将它们重定向到相应的页面。 For example, if a desktop user is accessing the mobile page http://m.mydomain.com/a-page , he is automatically redirected to desktop version of that page http://web.mydomain.com/a-page . 例如,如果桌面用户正在访问移动页面http://m.mydomain.com/a-page ,则该用户将自动重定向到该页面的桌面版本http://web.mydomain.com/a-page

I can't use .htaccess because my web-server is Nginx. 我无法使用.htaccess,因为我的Web服务器是Nginx。

If you're supporting modern browsers only, the URL API allows you to extract the path name from the URL. 如果仅支持现代浏览器,则URL API允许您从URL中提取路径名。 Refer to the below example, which converts the mobile URL to the web URL. 请参考以下示例,该示例将移动URL转换为Web URL。

 // Base URLs for mobile and web based sites. var mobileBaseUrl = "http://m.mydomain.com"; var webBaseUrl = "http://web.mydomain.com"; // The actual page URL var loc = "http://m.mydomain.com/what/ever/the/url"; var url = new URL(loc); // Converted location var result = `${webBaseUrl}${url.pathname}`; console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM