1

Not wanting to bloat up an .htaccess with 300 entries, what would be the javascript I could use to redirect to URLs based on a query string in the request to this single file. For example,

https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=57

The only part I care about is the 57 and then redirect it to wherever: https://www.anothercoolwebsite/secretworld/

In the following case, take the 34 and redirect:

https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=34 https://www.anoldwebsite.com/cool/file.html

Thank you!

  • Where do you want to take like id? – Ash Mar 10 '18 at 01:20
  • start by looking at `window.location`. You could use a regex pattern match on this to get the param you want, like this maybe `location.match(/LinkID=([0-9]+)/)`. – David784 Mar 10 '18 at 01:20
  • Yes, I referenced this in my tag. window.location was the first thing which came to mind. I am not sure how to incorporate the query string into a defined value for a redirect though. – David Turner Mar 10 '18 at 01:23
  • https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Ash Mar 10 '18 at 01:24

1 Answers1

2

This should do you fine. Keep in mind a server-side solution like a PHP script will work for more clients. Since you mentioned .htaccess, I think I should let you know about the fallback resource command

Anyways, here is the JS only solution

function parseString(){//Parse query string
    var queryString=location.search.substring(1);//Remove ? mark

    var pair = queryString.split('&'); //Key value pairs

    var returnVal={};
    pair.forEach(function(item,i){
        var currPair = item.split('=');//Give name and value

        returnVal[currPair[0]]=currPair[1];
    });

    return returnVal;
}

var links=["index", "about"];//Sample array of links, make sure this matches up with your LinkID
location.href=links[parseString().LinkID]+".html"; //Redirect based on LinkID
Ben
  • 2,200
  • 20
  • 30
  • Thank you, Ben! I am confused on how to associate several LinkIDs with their related URLs though. How would I send 57 to https://www.anothercoolwebsite/secretworld/ and 34 to https://www.anoldwebsite.com/cool/file.html for example? – David Turner Mar 12 '18 at 17:05
  • @DavidTurner In the second last line, I show an array, arrays start counting at zero, so "index" would be LinkID=0, "about" would be 1, etc etc – Ben Mar 12 '18 at 18:18