Redirect to different sites based on subdomains

Before I get to the meat of this post, you should know that when you want to simply redirect a site from http to https and you are using IIS, you can use one of two solutions:

  1. Add the following to the head:
    <meta http-equiv="refresh" content="0;URL='https://sarfraz.pro/'" />
  2. Use HTTP redirect in the site settings.

But what do you do if it is getting more complex that this, and you are presented with a scenario where:

    • http://sub1.example.com needs to go to https://sub1.example.com
    • http://sub2.example.com needs to go to https://sub2.example.com
    • http://example.com needs to go to http://www.example.com

With a little javascript, you can easily take care of this on the client side. Here is what you do.

Add the following to the head:

<script type="text/javascript">
function codeRedirect() {
if (window.location.hostname == "sub1.example.com" &&
window.location.pathname== "/" ) {
ref = 'https://sub1.example.com';
}
if (window.location.hostname =="sub2.example.com" &&
window.location.pathname== "/" ) {
ref = 'https://sub2.example.com';
}
else if (window.location.hostname =="example.com" &&
window.location.pathname== "/" ) {
ref = 'http://www.example.com';
}
window.location.href = ref;
}
</script>

Modify the body tag as such:

<body onload="codeRedirect()">

That’s it.

If you want to add more redirects into the function, just copy one of the “if” statements and paste them before “else if”. Then modify the hostname and ref with the new addresses. The hostname is what you want to direct from, and the ref is where you want to redirect to.

Filed under: JSTagged with: , ,

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *

Comment *
Name *
Email *
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.