Le-roy Staines
Le-roy Staines

Reputation: 2057

How to rewrite sub-folder with node express-urlrewrite?

Using express-urlrewrite, I can't figure out how to rewrite a sub-folder to effectively 'remove' it.

For example:

/en/ should become /

/en/home should become /home

My attempt so far:

app.use(rewrite(/^\/(en|es)\/[*]/, '/$1'));

How would I go about rewriting any en or es sub-folders?

Upvotes: 1

Views: 435

Answers (1)

Tomalak
Tomalak

Reputation: 338248

It's a regular regex, just test it outside of app.use.

The task is "remove /en or /es from the start of the string".

So let's write a regex that matches /en or /es at the start of the string. To avoid false positives (like /energy), let's make sure the following character, if any, is either a / or a ?:

"/en/home/bla".replace(/^\/(en|es)(?=[/?]|$)?/, '')

results in /home/bla.

app.use(rewrite(/^\/(en|es)(?=[/?]|$)?/, ''));

Regex breakdown (I've removed the regex-literal-specific escaping):

^                # start of string
/                # a forward slash
(                # group 1
  en|es          #   "en" or "es"
)                # end group 1
(?=              # look-ahead
  [/?]           #   one of forward slash, question mark
  |              #   or
  $              #   end of string
)                # end look-ahead

Upvotes: 1

Related Questions