Redirect to Firebase Hosting custom domain

前端 未结 3 1377
南笙
南笙 2020-12-03 05:10

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.firebaseap

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 05:57

    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"
              }
            ]
        }
    }
    

提交回复
热议问题