skip to Main Content

I’ve created a website, https://www.example.com. Now, I also created a mobile subdomain, where the four pages I originally created are combined into one long-scroll. When I manually go to m.example.com, this works just fine, but I’ve also printed some cards with QR code referencing the main domain previously. Since a QR code is more likely to be scanned from a mobile device, I want to add some code to the homepage that redirects any "mobile devices" to m.example.com automatically, but when I try implementing this in JS, my redirect ends up sending me to example.com/m.example.com instead. How can I redirect to the actual subdomain?

My code so far is pretty simple:

//Redirect to mobile subdomain if on mobile device
if (screen.width <= 699) {
    window.location = "m.example.com";
}

I’ve also tried document.location and I’ve tried referencing based on the document tree – tried pointing to ./mobile/index.php, where the root folder is where the main homepage’s index.php resides, and so where I figured I’d be redirecting from. Note that my JS is in the ./inc directory, but whether I include ./ or not (or even ././), computer says no 🙁
I’ve also tried looking at .htaccess, which seems fine for referrals, but I didn’t see anything about how to do a conditional referral there either. I’m using PHP and JS, and of course HTML and CSS, so any solution using those languages is preferred, but I’ll take whatever works.

2

Answers


  1. The issue with your implementation is that you have not added http or https protocol before the domain. Doing that will do the job.
    Also, here is an implementation of how you can achieve it:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>My App</title>
      <script>
        function isMobileMedia() {
            console.log(screen.width)
            return (screen.width <= 699);
        }
    
        if (isMobileMedia()) {
            window.location.href = "http://m.example.com";
        }
      </script>
    </head>
    <body>
      <h1>Welcome to example.com</h1>
    </body>
    </html>
    
    Login or Signup to reply.
  2. You need to include the https:// protocol:

    window.location = 'https://m.example.com/';
    

    Explanation:

    When you declare URLs, you can either declare:

    1. Absolute URLs, which start with the protocol (https://, http:// etc.)
    2. Relative-to-root URLs, which start with a /, indicating the root folder of your domain
    3. Relative URLs, which start from the folder which the browser is currently pointing at

    To re-locate to a subdomain, you don’t really have any option, but 1.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search