javascripthttp-redirectconditional-statementssubdomain

Conditional redirect to mobile subdomain


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.


Solution

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