Last Updated : Jul 1, 2023
URL redirection, also known as URL forwarding, is a method of redirecting a web page to another web page automatically.
The redirected page is frequently on the same website, but it can also be on another website or on a separate web server.
It's important to note that window.location.href loads pages from the browser's cache rather than sending requests to the server.
In case, if you have an older version of the page in your cache, it will redirect to it rather than loading a new page from the server.
<html> <head> </head> <script> window.location.href="http://newURL.com"; </script> </body> </html>
- For instance, if you're redirecting URL A to URL B, simply enter URL B here, as demonstrated in the example above.
Redirection using replace() function
In jQuery, the replace() function of the window.location object can also be used to redirect to a web page.
The current URL is removed from the history and replaced with a fresh URL using this method. Let's of how this function can be used to redirect traffic.
<html> <head> </head> <script> window.location.replace("url"); </script> </body> </html>
- If you want to redirect to a new page but don't want the user to be able to return to the previous one using the back button, use the replace() method.
Using the window assign() function, redirection can be done.
Unlike the replace() function, this code adds a new URL to the history stack and redirects to it, allowing you to use the back button to return to the original document.
This is an example of how to use this method to redirect to a new url.
<html> <head> </head> <script> window.location.assign("url"); </script> </body> </html>
- Use the assign() method for redirection if you want the user to be able to return to original document using the back button.
You may need to redirect from one page to another for various reasons. As much as possible, configure these on the server.