0

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.

macbert
  • 772
  • 2
  • 11
  • 29
  • Hi Asaad, always try to break down the issue you have into its parts. Note that the actual problem you have has nothing to do with redirection, it's only about figuring out what the current URL is. And you already have what you need: `location.href` –  Jul 07 '21 at 07:17
  • If it is just one specific URL I wouldn't do this on client side with javascript. This is something your Webservers vhost file should take care of. – macbert Jul 07 '21 at 09:19

1 Answers1

0

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Cheers! This works fine for me, I have some parameters with the old URL, despite what parameter I have It only grabs the base URL and redirects to the new one. – Asaad Qamar Jul 07 '21 at 07:32
  • location.href contains the full URL including parameters – mplungjan Jul 07 '21 at 07:46