Learn how and why to redirect your website visitors to another URL, with JavaScript’s window.location
object.
How to page redirect
To redirect your website visitors to a new URL all you need is to execute the following JavaScript on the webpage you want to redirect from:
window.location = "https://wheretoredirect.com"
You can either insert the code in an external .js
file or place it inline in the head section (<head>
) of your webpage:
<script type="text/javascript">
window.location = "https://wheretoredirect.com"
</script>
Now any website visitor that goes to https://yourwebsite.com
will immediately get redirected to the URL you specify as your window.location
value.
You can use page redirecting to direct website visitors to:
- a different website domain (from
oldsite.com
tonewsite.com
). - a different page/post on the same domain (
yourwebsite.com/your-post
). - a subfolder on the same domain (
yourwebsite.com/archive
). - a subdomain (
support.yourdomain.com
).
Make sure that you use the correct website protocol (https
, www
, https://www
, etc.) when you redirect your users.
Show message before redirecting site visitor
To enhance the user experience you can display a message to your site visitors and delay the redirection with a countdown timer. This way your visitors won’t get confused as to why they’re suddenly sent to a different URL or domain.
Let’s take the same code from earlier, but now we also add the following:
- a message that explains why they’re getting redirected.
- a countdown timer that executes the redirection code after 5 seconds.
Show message + countdown timer:
function showMessageBeforeRedirect() {
window.location = "https://wheretoredirect.com"
}
document.write("You’ll be redirected to our new domain in 5 seconds :-)")
setTimeout("showMessageBeforeRedirect()", 5000)
The 5000
value is milliseconds.
Try adding the code to your website <head>
like you did earlier:
<script type="text/javascript">
function showMessageBeforeRedirect() {
window.location = "https://wheretoredirect.com"
}
document.write("You’ll be redirected to our new domain in 5 seconds :-)")
setTimeout("showMessageBeforeRedirect()", 5000)
</script>
Why would you redirect your visitors?
Here are a few reasons why you’d want to redirect users in real-life projects:
- You switched to a new domain name and you want to make sure that people who used to visit your old domain are directed to the new domain.
- You have different versions of your website, e.g. one for legacy browsers and one for modern browsers, and you want to make sure that users land on the one that matches their browser.
- You have different language versions of the same website, and you want to make sure that e.g. users with Italian language settings in their browser are directed to
yourwebsite.com/it
.