Dealing With Case Insensitive URLs When Hosting A Site on S3

I'm a big fan of hosting static sites on S3. You really can't beat the value proposition of uptime, no management, and cost. I host this site on S3 for those reasons.

There is a downside to hosting on S3 though. S3 is case sensitive. Typically this isn’t a problem as generally people type in our main domain name, or click through from search results.

You run into two problems with case sensitivity:

1. People don’t expect it, so when setting up a link for ad or giving someone a url they may inadvertently mix case. Then their link won’t work.

2. It’s not uncommon to use unlinked landing pages in offline collateral. In this case people are typing in the URLs, and case sensitivity can have them landing on a 404 page instead of the content they were looking for.

There is a pretty easy way around this.

1. Lowercase all of your URLs

Making sure all of your URLs are lowercase gives you a base URL standard to work from.

2. Define an Error page on your S3 bucket

The Error Page will be displayed anytime the browser gets a 404, which is going to happen if someone uses upper case in a URL now that you have all lower case. When the Error Page is shown, a redirect isn’t fired, so the URL stays the original URL the user typed in.

3. Use JavaScript to Lowercase, Detect and Redirect

Now you use JavaScript on your Error Page to lowercase your URL, do a quick Ajax call to see if it exists in the lower case form. If the page exists you redirect to the lower case version, if it doesn't exist then display or redirect to your custom 404 page.

Here is a snippet of code that I used as my Error Page to do that. In this case the existing 404 action for the site was to redirect to the homepage.

    <script>
        var url = $(location).attr('href');
        url = url.toLowerCase();
        $.ajax({
            url: url,
            method: "HEAD"
        })
        .done (function() {
            window.location = url;
        })
        .fail (function() {
            window.location = '/';
        });
    </script>

Give it a try on this post, go upper case some random characters in your address bar.