Redirect default URL to custom URL in Firebase Hosting

Redirect default url to custom url in firebase hosting
Redirect default url to custom url in firebase hosting

Did you ever need to redirect the default URL of firebase hosting to a custom URL? You may ask me why do you need to do so. There are a couple of cases that we need to do so. I’m going to explain a scenario that I’ve needed to redirect the default URL to a custom URL in Firebase Hosting.

My client asked me to host his web site on Firebase Hosting and at that time he was not configured with the proper domain name. So I deployed his website and I gave him the deployed URL something like https://myapp.firebaseapp.com. So he was happy and shared that with few people that need that to test. A few days later he configured his proper domain name in firebase hosting and it is working perfectly. But the problem is the default URL that I have shared with him previously also working. He wanted to redirect that URL to the custom domain that he configured.


The problem here is firebase does not allow to cancel or redirect the default URL. So adding redirects in firebase.json won’t work. So we have to do it on our own. The simplest way that I realize is to do the redirection with JavaScript. So what you have to do is adding the below script to the bottom of your index.html page.

<script type="text/javascript">
        if (location.hostname.indexOf('custom.domain') === -1) {
            location.replace("https://custom.domain");
        }
</script>

What this script does is if the URL hostname is not equal to our custom domain the rewrite the URL to the custom domain. This method works for all the browsers that enabled the JavaScript.

Hope this will help you if you had to face the same situation as me. You can see more details here.

If you facing any performance issues with Android Studio this guide will help you to Fine-tune Android Studio with JVM options.

Happy Coding!