【问题标题】:Firebase redirect using RegexFirebase 使用正则表达式重定向
【发布时间】:2021-01-19 00:16:45
【问题描述】:

我的目标是将任何不以特定符号 ("#") 开头的 URL 重定向到不同的网站。 我正在使用 Firebase 托管,并且已经在重定向中尝试了 Regex 函数来实现这一点。我在重定向上关注了这个 firebase documentation,但是因为我是正则表达式的新手,所以我认为我的错误可能是我的正则表达式代码。

我的目标:

  • mydomain.com/anyNotStartingWith# => otherdomain.com/anyNotStartingWith#
  • mydomain.com/#any => mydomain.com/#any

我的代码:

{
  "hosting": {
    ...
    "redirects": [
      {
        "regex": "/^[^#]:params*",
        "destination": "otherdomain.com/:params",
        "type": 301
      }
    ],
    ...
  }
}

【问题讨论】:

  • 试试"regex": "/(?P<params>[^/#][^/]*)",或"regex": "/(?P<params>[^/#].*)"
  • @WiktorStribiżew 感谢您的帮助,两者都有效!有没有办法在这个表达式中添加一些东西来检查 URL 是否以 .js 结尾并且也不允许这样做。这样 mydomain.com/any.js 也不会被重定向。

标签: regex firebase redirect firebase-hosting


【解决方案1】:

你可以使用

"regex": "/(?P<params>[^/#].*)"

关键是您需要一个捕获组来匹配并捕获您要在destination 中使用的部分。所以,在这种情况下

  • / - 匹配 /
  • (?P&lt;params&gt;[^/#].*) - 命名捕获组params(您可以使用:params 引用destination 中的组):
    • [^/#] - 除/# 之外的任何字符
    • .* - 除换行符之外的任何零个或多个字符,尽可能多

为避免与.js 匹配文件,您可以使用

/(?P<params>[^/#].*(?:[^.].{2}$|.[^j].$|.{2}[^s]$))$

this RE2 regex demo

Regex: match everything but specific pattern 上查看有关如何否定模式的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-14
    • 2012-06-21
    • 2014-12-05
    • 1970-01-01
    • 2013-07-25
    • 2018-04-19
    • 1970-01-01
    相关资源
    最近更新 更多