重定向到 Firebase 托管自定义域

Redirect to Firebase Hosting custom domain

我已经使用 Firebase 托管设置了一个自定义域(例如 myapp.domain.com)。

如何重定向(或关闭)默认的 Firebase 托管 URL(例如 myapp.firebaseapp.com),以便只能从自定义域访问该应用程序?

您无法关闭子域。您的应用将始终在 https://myapp.firebaseapp.com 您设置的任何自定义域上可用。

要重定向用户,您可以将 canonical link 添加到您的 HTML:

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

在 Google 网站管理员中心博客的 Specify your canonical 中阅读更多相关信息。

您可以使用 Firebase Functions。

125K 免费 invocations/month - https://firebase.google.com/pricing

一个使用 Express 中间件的例子:

// 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);

必须将导出的函数名称添加到 firebase.json 中的重写,例如:

{
    "hosting": {
        "public": "public",
        "rewrites": [
          {
            "source": "**",
            "function": "redirectFunc"
          }
        ]
    }
}

除了 Frank van Puffelen 的回答中提到的指定规范 link 之外。我们还可以添加前端 JavaScript 代码来执行实际的重定向,而无需公开默认值 url.

if (location.hostname.indexOf('custom.url') === -1) {
    location.replace("https://custom.url");
}