Verpz Verpz - 7 months ago 10
Javascript Question

If URL Contains a Specific Port Redirect With JavaScript

I need to redirect a url such as http://forum.domain.com:4567
to https://forum.domain.com. The code will be run site wide, so it must only redirect when a visitor goes to http://forum.domain.com:4567

I have tried this, but it loops:

<script>
if (window.location.href = "http://forum.domain.com:4567") {
window.location = "https://forum.domain.com";
}
</script>

Answer

window.location is a Location type, which is similar to the URL type, meaning it should have a port property.

You can do something like:

if (window.location.port === "4567"){
    window.location = "https://forum.domain.com";
}

or in case you want a little more extensibility:

if (window.location.port === "4567"){
    window.location = window.location.href.replace(':' + window.location.port, "");
}