我为移动 (http://m.mydomain.com) 和桌面 (http://web.mydomain.com) 用户设置了不同的域名。我目前正在使用以下 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>
但问题是:用户被重定向到主页 ( 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);
关于javascript - 使用 Javascript 重定向到桌面/移动版本的相应页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412315/