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!

4
  • Where do you want to take like id? Commented Mar 10, 2018 at 1: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]+)/). Commented Mar 10, 2018 at 1: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. Commented Mar 10, 2018 at 1:23
  • stackoverflow.com/questions/901115/… Commented Mar 10, 2018 at 1:24

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, Ben! I am confused on how to associate several LinkIDs with their related URLs though. How would I send 57 to anothercoolwebsite/secretworld and 34 to anoldwebsite.com/cool/file.html for example?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.