Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect extra forward slash in URL with IIS

This question will work best with examples.

Say my web app is hosted at http://example.com/WebApp/

According to Microsoft, IIS will redirect if the trailing forward slash is missing. And this works as expected: a request sent to http://example.com/WebApp is redirected to http://example.com/WebApp/.

Now in my case, someone bookmarked the URL with an extra forward slash: http://example.com/WebApp//. This will load the web app as expected but now all the relative URLs are wrong. So if I call another app on the same domain, for example ../AnotherApp/SomePage.aspx, then it will try to load /WebApp/AnotherApp/SomePage.aspx instead of correctly loading /AnotherApp/SomePage.aspx.

How can I redirect http://example.com/WebApp// to http://example.com/WebApp/?

like image 525
styfle Avatar asked Nov 13 '22 07:11

styfle


1 Answers

It appears difficult to do this with server side script alone. Perhaps doing a redirect in JavaScript would suffice?

<html>
<head>
<script type="text/javascript">
(function () {
    var protocol = location.href.substr(0, location.href.indexOf("://"));
    var restOfUrl = location.href.substr(location.href.indexOf("://") + "://".length);
    if (restOfUrl.match(/\/\//)) {
        location.href = protocol + "://" + restOfUrl.replace(/\/\//g, "/");
    }
})();
</script>
</head>
<body>
...
</body>
</html>

Also, you should consider setting a canonical link in your page so that search engines index things correctly.

like image 142
dana Avatar answered Nov 14 '22 23:11

dana