is it possible to redirect the hostname of the URL using javascript?
If URL contains "content/articles", it should remain in the same URL. Otherwise, it should redirect all other URLs from www to www1.
I think i got the "/content/articles" part but window.location.replace doesnt seem to work.
For example:
<script type="text/javascript">
window.onload = function() {
if (window.location.href.indexOf("/content/articles") > -1) {
// Do not redirect
} else {
// Redirect from www to www1
window.location.replace(window.location.protocol + "//" + window.location.hostname.replace("www", "www1")+window.location.pathname);
}
}
</script>
You can redirect a web page to another page in a number of ways including server-side redirects, HTML meta refresh redirects and JavaScript redirects.
href Property. The simplest and most common way to use JavaScript to redirect to a URL is to set the location property to a new URL using window. location. href.
You can use window.location.href.replace()
let url = window.location.href.replace('://www','://www1')
console.log(url);
Here is the example
<script type="text/javascript">
window.onload = function() {
if (window.location.href.indexOf("/content/articles") > -1) {
// Do not redirect
} else {
// Redirect from www to www1
window.location.href = window.location.href.replace('://www','://www1');
}
}
</script>
replace('://www','://www1')
Also fine since it replace only first occurrence
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With