lwsjs / local-web-server

A lean, modular web server for rapid full-stack development.
MIT License
1.2k stars 85 forks source link

Rewrite appends original path to rewritten path. #150

Closed villelahdenvuo closed 4 years ago

villelahdenvuo commented 4 years ago

Maybe I'm configuring something wrong, but it seems like rewrite it doing something it shouldn't.

My config ```js module.exports = { hostname: 'localhost', port: '4200', directory: './dist', rewrite: [ { from: /\/(fi|en|sv)(?:\/(?!.*\..{2,5}$))/, to: '/$1/index.html', } ], }; ```

Expected output:

{
  'middleware.rewrite.local': {
    from: '/en/product/97/card-150-x-100-mm-2-page/details',
    to: '/en/index.html'
  }
}

Actual output:

{
  'middleware.rewrite.local': {
    from: '/en/product/97/card-150-x-100-mm-2-page/details',
    to: '/en/index.htmlproduct/97/card-150-x-100-mm-2-page/details'
  }
}

I don't know why is it appending the remainder of the path even though I'm not telling it to do so and I even tried using a non-capturing group in the regex.

I was able to get it to work by adding ?file= to the rewrited file so it loads the correct file, but if you can tell me the problem with my config I can improve the docs about it.

75lb commented 4 years ago

Hi, each rewrite rule is passed to and handled directly by path-to-regexp (also used by Express) so it helps to know their syntax.

This config seems a more straight-forward way to achieve the same thing.

{
  rewrite: [
    {
      from: '/:lang/(.*)',
      to: '/:lang/index.html'
    }
  ]
}

Does that help?

villelahdenvuo commented 4 years ago

Hey, I think you misunderstood the intent of my regex, which was to detect file extensions (to not redirect those). I realized that the problem was that the regex was not matching the full path so the remainder of the path was appended to the result.

I tweaked my config like this and it works as long as our urls don't include dots:

{
    from: /\/(fi|en|sv)\/[^.]+$/,
    to: '$1/index.html',
}

Edit: Using the path-to-regexp syntax it can be written as:

{
    from: '/:locale/([^.]+)*',
    to: '/:locale/index.html',
}
75lb commented 4 years ago

excellent, nice clean solution 👍