2

I have different domain names for mobile (http://m.mydomain.com) and desktop (http://web.mydomain.com) users. I am currently using following Javascript code to redirect my desktop users accessing mobile URLs to desktop URLs.

<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. 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.

I can't use .htaccess because my web-server is Nginx.

HSGreen
  • 31
  • 1
  • 1
    Refer to [this post](https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser). Get yourself similar function and check if user visits your site using a mobile brower. If so, then redirect to the mobile site. – 31piy Mar 29 '19 at 07:23
  • I'm already able to detect the mobile user and redirect them. I am asking how do I redirect them to the same page on desktop URL. – HSGreen Mar 29 '19 at 09:31

1 Answers1

0

If you're supporting modern browsers only, the URL API allows you to extract the path name from the URL. Refer to the below example, which converts the mobile URL to the 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);
31piy
  • 21,164
  • 6
  • 40
  • 57