user3108698
user3108698

Reputation: 719

How to redirect url using javascript query

How do I redirect conditionally with query /xxx?xxx in the url link?

For example, anyone who come to my site with the below two link should be redirected to different pages.

mysite.com/contest?a => mysite.com/contest-a
mysite.com/contest?b => mysite.com/contest-b

Can this be done using both js and meta refresh?

How do I do this using .htaccess?

Upvotes: 1

Views: 96

Answers (5)

Israfil Havilah
Israfil Havilah

Reputation: 761

If you're ok doing this kind of operation on the client side, you could embed the following snippet on your landing page (the page where the arriving user will be redirected), just after the <head> tag:

<script type="text/javascript">
  var mapReferrer = function() {
    var gotoURL;

    switch(document.referrer) {
      case "https://www.google.com":      gotoURL = "http://<yoursite>/arrivedFromSearchEngine"; break;
      case "https://www.facebook.es":     gotoURL = "https://<yoursite>/engageFBusers"; break;
      case "http://<yoursite>/contest?b": gotoURL = "http://<yoursite>/contest-b"; break;
    };

    if (gotoURL) window.location = gotoURL;
  };

  window.onload = mapReferrer;
</script>

Upvotes: 0

Pablo Mescher
Pablo Mescher

Reputation: 27427

It's not possible to change the url without refreshing the page (except for hashes), and thus you would be better off not using that url in the first place to avoid unnecessary requests and hassle for the user. You could take a look at mod_rewrite which does that (transform a "nice url" from the user into an "ugly url" that your server actually understands)

In your example, a possible rule might be

RewriteRule  ^mysite.com/contest-{.+}  /mysite.com/contest?$1

Upvotes: 0

Durai
Durai

Reputation: 582

you can use the below script to do the re-direction.

window.onload = function()
{
   var location = window.location;
   if(location.indexOf("contest?a") > -1)
   {
         window.location.href = "mysite.com/contest-a";
   }
   else
   {
         window.location.href = "mysite.com/contest-b";
   }
}

Upvotes: 0

Sergey Yarotskiy
Sergey Yarotskiy

Reputation: 507

Use

location.href 

to detect url, where you are now. And

window.location.replace('mysite.com/contest-a ');

to do redirect. But probably it is better to do it on server side, since it will be faster.

Upvotes: 0

adeneo
adeneo

Reputation: 318162

If there is a querystring, replace the first instance of ? with -

if (window.location.search.length)
    window.location.href = window.location.href.replace('?','-');

Upvotes: 1

Related Questions