In JavaScript, we can redirect to a relative URL by using the window.location object and setting it to the relative path we want.
window.location.href = "some-page.com";
Here are some quick relative redirect examples which we will go over below.
window.location.href = "some-page.com";
//This redirect will be relative to our CURRENT directory
window.location.href = "/some-page.com";
//This redirect will be relative to our HOME directory
window.location.href = "../some-page.com";
//This redirect will be relative to one directory ABOVE our current directory
window.location.href = "../../some-page.com";
//This redirect will be relative to TWO directories ABOVE our current directory
window.location.href = "new-directory/some-page.com";
//This redirect will be relative to the directory new-directory in our current directory
Let’s go over a bunch of examples to show how redirecting to a relative URL in JavaScript works.
In these examples, we will simply show the JavaScript setup and the page you would get redirected to.
window.location.href = "some-page.com";
#Output
https://daztech.com/some-page.com
Since this page is currently in the main directory “https://daztech.com/”, by just putting some-page.com, it will go to this page in the same directory. Hence https://daztech.com/some-page.com
.
Let’s show another example assuming we are in a new directory of our site: https://daztech.com/category/javascript/
window.location.href = "some-page.com";
//Assuming our page is located at https://daztech.com/category/javascript/javascript-redirect-to-relative-url
#Output
https://daztech.com/category/javascript/some-page.com
If however, we wanted to go to the relative URL https://daztech.com/some-page.com
from our new location, we would simply have to change our JavaScript code a little.
window.location.href = "/some-page.com";
//Assuming our page is located at https://daztech.com/category/javascript/javascript-redirect-to-relative-url
#Output
https://daztech.com/some-page.com
By adding the /
before our page, we are saying we want to redirect to our domain directory, and go to the page via that path.
Let’s see another example:
window.location.href = "../some-page.com";
//Assuming our page is located at https://daztech.com/category/javascript/javascript-redirect-to-relative-url
#Output
https://daztech.com/category/some-page.com
The ../
will make us go up one directory from where we were.
And finally:
window.location.href = "another-directory/some-page.com";
//Assuming our page is located at https://daztech.com/category/javascript/javascript-redirect-to-relative-url
#Output
https://daztech.com/category/javascript/another-directory/some-page.com
Hopefully this article has been useful for you to understand how to use JavaScript to redirect to a relative url.