Redirect to a specific URL on page load JavaScript?

1.3k Views Asked by At

I have a problem with redirection. What I am trying to do is: "When a specific page off one website is loaded, it should redirect to another page/URL in the same window".

I have this code

window.onload = function() {
  location.href = "https://www.javascripttutorial.net/";
}

But the problem is where am I going to put my old URL which should be redirected because I am redirecting only a specific page to another website.

Kindly help me out with this.

1

There are 1 best solutions below

2
On

You can do

if (location.href.indexOf('oldpage') !=-1) 
  location.replace("https://www.javascripttutorial.net/")

which will not break the user's back button

However: It sounds like you should add the url in the .htaccess and have the server do the redirect instead: redirect a specific url to another url with .htaccess