2

My goal is to redirect any URL that does not start with a specific symbol ("#") to a different website. I am using Firebase Hosting and already tried the Regex function in redirect to achieve this. I followed this firebase documentation on redirects but because I new to regular expressions I assume that my mistake might be my regex code.

My Goal:

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

My Code:

{
  "hosting": {
    ...
    "redirects": [
      {
        "regex": "/^[^#]:params*",
        "destination": "otherdomain.com/:params",
        "type": 301
      }
    ],
    ...
  }
}
LP Square
  • 927
  • 1
  • 10
  • 17
  • 2
    Try `"regex": "/(?P[^/#][^/]*)"`, or `"regex": "/(?P[^/#].*)"` – Wiktor Stribiżew Oct 03 '20 at 16:34
  • @WiktorStribiżew Thanks for your help, both work! is there a way to add to this expression something to check if the URL ends with .js and also don't allow this. so that mydomain.com/any.js is not redirected either. – LP Square Oct 03 '20 at 18:12

1 Answers1

2

You can use

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

The point is that you need a capturing group that will match and capture the part you want to use in the destination. So, in this case

  • / - matches /
  • (?P<params>[^/#].*) - Named capturing group params (you can refer to the group from the destination using :params):
    • [^/#] - any char other than / and #
    • .* - any zero or more chars other than line break chars, as many as possible

To avoid matching files with .js, you can use

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

See this RE2 regex demo

See more about how to negate patterns at Regex: match everything but specific pattern.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563