- The old domain name is changed to a new domain
- Submission and Authorization of a form
- On the base of the browser or language of the user
- Redirect from HTTP to HTTPS
This article explains a few different ways to redirect a page.
In this method, you simply provide the URL to which you want to redirect the user.
The syntax for another method of redirecting a user to a new URL is as follows:
In this functional syntax, you provide the URL to which you want to redirect, and whenever this function is called, you will be redirected to that specific URL.
Here, “replace” and “assign” do the same task but with a subtle difference. They both redirect to a new URL, but “replace” does not take the record of history and the user cannot go back to the old URL or previous page. Meanwhile, “assign” keeps the history record and allows the user to go back to the previous page.
We will now look at some examples of both syntaxes.
First, we will create an on-click function on a button.
This function will redirect the user to the website “https://www.linuxhint.com.”
window.location.href = "https://www.linuxhint.com"
Now, if the user clicks on the button, they will be redirected to linuxhint.com
In this next example, say, you want to redirect the user from an old domain to the new domain. For testing purposes, suppose the current address is the localhost, but whenever the user enters the URL of the localhost, the user gets redirected from the localhost to the new URL, which is linuxhint.com in this example. This is easier to do than you may think. To do this, simply use the syntax of the second redirect method:
Now, if the user enters the localhost URL, they will be redirected to linuxhint.com. But, if you look at the top-left button of the browser for going back to the previous page:
the button is dulled and the browser is not allowing us to go back to the previous page. However, if you want to keep this option for the user, you can use “assign” instead of “replace.”
And now, if you look at the top-left button of the browser for going back to the previous page:
The button is not dulled. You can go back to the previous page.
It is recommended to use “replace” instead of “assign,” here, because the purpose of redirecting to a new URL is that the old URL is not working or not available anymore.