22

I have setup a custom domain with Firebase Hosting (eg. myapp.domain.com).

How can one redirect (or turn off) the default Firebase Hosting URL (eg. myapp.firebaseapp.com) so that the app is only accessible from the custom domain?

bostondv
  • 415
  • 4
  • 8

3 Answers3

18

You cannot turn off the subdomain. Your app will always be available on https://myapp.firebaseapp.com and whatever custom domain you've set up.

To redirect people, you can add a canonical link to your HTML:

<link rel="canonical" href="http://myapp.domain.com/" />

Read more about that in Specify your canonical on the Google Webmaster Central Blog.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 3
    I've added this to my index.html's and don't get redirected when using the firebase provided url. Is this only for Search Engines? (e.g. I'll be redirected if I clicked it using google?) – Jonathan002 Jun 11 '18 at 04:14
  • @Jonathan002 you can add JavaScript redirect as mentioned in my answer in addition to adding canonical link. – Abdul Rauf May 31 '20 at 11:52
4

You could use Firebase Functions.

Free for 125K invocations/month - https://firebase.google.com/pricing

An example using Express middleware:

// functions/index.js

const functions = require('firebase-functions');
const express = require('express');
const url = require('url');

const app = express();

// Allowed domains
let domains = ['localhost:5000', 'example.com'];
// Base URL to redirect
let baseurl = 'https://example.com/';

// Redirect middleware
app.use((req, res, next) => {
    if (!domains.includes(req.headers['x-forwarded-host'])) {
        return res.status(301).redirect(url.resolve(baseurl, req.path.replace(/^\/+/, "")));
    }
    return next();
});

// Dynamically route static html files
app.get('/', (req, res) => {
    return res.sendFile('index.html', { root: './html' });
});

// ...

// 404 middleware
app.use((req, res) => {
    return res.status(404).sendFile('404.html', { root: './html' });
});

// Export redirect function
exports.redirectFunc = functions.https.onRequest(app);

The exported function name must be added to rewrites in firebase.json e.g.:

{
    "hosting": {
        "public": "public",
        "rewrites": [
          {
            "source": "**",
            "function": "redirectFunc"
          }
        ]
    }
}
seht
  • 43
  • 4
  • I think this can be achieved without rewrites and just implementing redirect middleware into your http functions server – Jeff Voss Feb 06 '23 at 19:51
3

In addition to specifying canonical link as mentioned in Frank van Puffelen's answer. We can also add front end JavaScript code to do the actual redirect like this without disclosing default url.

if (location.hostname.indexOf('custom.url') === -1) {
    location.replace("https://custom.url");
}
Max
  • 739
  • 2
  • 8
  • 23
Abdul Rauf
  • 5,798
  • 5
  • 50
  • 70