Search code examples
javascriptnode.jsexpresssubdomain

How to redirect users to a subdomain based on IP location?


I am using Node Express for my website and I would like to redirect users based on their current location, for example, if users in Singapore open site.com, then redirect them to the subdomain sg.site.com (this one is hosted on the same server as site.com). I am able to find user's IP address and location but how to redirect them to the proper subdomain?


Solution

  • If you mean from server-side Express code, with res.redirect:

    res.redirect([status,] path)

    Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.

    res.redirect('/foo/bar');
    res.redirect('http://example.com');
    res.redirect(301, 'http://example.com');
    res.redirect('../login');
    

    If you mean client-side, assign to the location object.

    Replace the current document with the one at the given URL:

    function goMoz() {   
       window.location = "http://www.mozilla.org";  
    }