feat: Add redirect option#93
feat: Add redirect option#93mcollina merged 4 commits intofastify:masterfrom coreyfarrell:directory-redirect
Conversation
This adds an option to redirect requests for directories when the tailing slash is missing. Fixes #92
* Support `redirect: true` for folders which provide an index file. * Support the `index` option.
| index: 'index.html' | ||
| } | ||
|
|
||
| const fastify = Fastify() |
There was a problem hiding this comment.
Can you add another test with ignoreTrailingSlash: true?
There was a problem hiding this comment.
I tested redirect: true, wildcard: true with ignoreTrailingSlash: true on the server and it worked as expected without any further changes.
As is redirect: true, wildcard: false cannot be used on a server with ignoreTrailingSlash: true. To fix this would require a way to determine if ignoreTrailingSlash is enabled. In my working copy I edited node_modules/fastify/fastify.js so that the server object is created with:
const fastify = {
ignoreTrailingSlash: options.ignoreTrailingSlash,
[kChildren]: []
}Then I made my local copy of fastify-static check if fastify.ignoreTrailingSlash is enabled to know how to register routes. The problem is that fastify.get('/static/') creates two routes so wildcard: false needs to know to not also setup fastify.get('/static'), as it stands find-my-way throws an assertion. I'd prefer to not use a try / catch block to suppress this assertion for risk of potentially suppressing errors.
An alternative would be for fastify-static to register fastify.get(pathname.replace(/\/$/, '')) before fastify.get(pathname), and fix find-my-way to only register the ignoreTrailingSlash route if it doesn't already exist. This would probably be cleaner for fastify-static.
There was a problem hiding this comment.
Can you please document the behavior that is not supported? We might want to implement this in a follow-up a PR if there is a need.
There was a problem hiding this comment.
Done.
I looked at find-my-route again, it appears that /path registers /path/ and /path/ registers /path. So probably the best fix would be to honor ignoreTrailingSlash: false option for find-my-way routes to override the global option, that way we could pass ignoreTrailingSlash: false for wildcard: false, redirect: true.
This adds an option to redirect requests for directories when the
tailing slash is missing.
Fixes #92