Skip to content

Instantly share code, notes, and snippets.

@krohrbaugh
Created May 29, 2009 01:09
Show Gist options
  • Save krohrbaugh/119709 to your computer and use it in GitHub Desktop.
Save krohrbaugh/119709 to your computer and use it in GitHub Desktop.
Poor man's subdomain redirect using JavaScript
var hostarray = new Array();
hostarray["subdomain.somewhere.com"] = "subdomain.somewhere.com/application/home.html";
function redirect()
{
//Obtain the host name in lowercase format
var lhost = new String(location.host);
lhost = lhost.toLowerCase();
//Does a redirect exist for this host?
if (typeof(hostarray[lhost])!='undefined')
{
//Replace the first instance in the location - this retains all extensions/parms
var newURL = String(location.href);
var lnewURL = newURL.toLowerCase();
//Get the exact position of the text to replace
//(the text should logically be present but we'll confirm it just in case)
var pos = lnewURL.indexOf(lhost);
if (pos>=0)
{
var hostname = new String(hostarray[lhost]);
// Strip off leading slashes - this will interfere with parms
var parms = newURL.substr(pos+lhost.length);
if ((parms.length > 0) && ((parms.charAt(0) === '\\') || (parms.charAt(0) === '/')))
parms = parms.substr(1,parms.length-1);
// Build the new URL with the new replacement for the hostname
newURL = newURL.substr(0,pos) + hostname + parms;
//We must be careful NOT to pass any ending slashes because this
//could interfere with HTM files and parameters in the replacement URL
//(e.g., http://shortcut.net/ is replaced by http://replacement.net/home.htm/
// we don't want the slash after .htm, now do we?)
lastchar=newURL.charAt(newURL.length-1);
if ((lastchar=='\\') || (lastchar=='/'))
newURL = newURL.substr(0,newURL.length-1);
// We're ready to load the new URL
location.replace(newURL);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment