javascript - 使用 Javascript 重定向到桌面/移动版本的相应页面

标签 javascript redirect

我为移动 (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/

相关文章:

php - 使用 PHP 更改用户代理

redirect - 如何从 nginx 发出相对 URL 重定向?

typescript - Nestjs如何在没有中间链接的情况下进行重定向

.htaccess 将文件夹重定向到 url

javascript - AngularJs:通过服务传递 $scope 变量

javascript - 使用 Array.reduce() 从获取 promise 中提取 JSON 数据

javascript - Html5节点图?

javascript - 如何使用字符串访问嵌套对象值以便我可以编辑?

javascript - jPlayer 不会在 iOS 上播放第二次(有时)

Facebook 共享链接在页面存在时返回 404 重定向错误