我有移动(http://m.mydomain.com)和桌面(http://web.mydomain.com)用户的不同域名。我目前正在使用以下Javascript代码将访问移动网址的桌面用户重定向到桌面网址。
<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>
但问题是:用户被重定向到主页(http://web.mydomain.com),无论他在哪个页面。我想将它们重定向到相应的页面。例如,如果桌面用户正在访问移动页面http://m.mydomain.com/a-page,则会自动将其重定向到该页面http://web.mydomain.com/a-page的桌面版本。
我不能使用.htaccess,因为我的网络服务器是Nginx。
如果您仅支持现代浏览器,则URL API允许您从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);