繁体   English   中英

重定向到 Firebase 托管自定义域

[英]Redirect to Firebase Hosting custom domain

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

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

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

要重定向人员,您可以向 HTML 添加canonical链接:

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

在 Google 网站站长中心博客上的指定您的规范中阅读更多相关信息。

您可以使用 Firebase 函数。

每月 125K 次调用免费 - 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 的回答中提到的规范链接之外。 我们还可以添加前端 JavaScript 代码来执行这样的实际重定向,而无需公开默认 url。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM