diff --git a/README.md b/README.md index b0e3b51..c39e8d0 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ $ npm install koa-send - `index` Name of the index file to serve automatically when visiting the root location. (defaults to none). - `gzip` Try to serve the gzipped version of a file automatically when `gzip` is supported by a client and if the requested file with `.gz` extension exists. (defaults to `true`). - `brotli` Try to serve the brotli version of a file automatically when `brotli` is supported by a client and if the requested file with `.br` extension exists. (defaults to `true`). - - `format` If not `false` (defaults to `true`), format the path to serve static file servers and not require a trailing slash for directories, so that you can do both `/directory` and `/directory/`. + - `format` If not `false` (defaults to `'follow'`), format the path to serve static file servers and not require a trailing slash for directories, so that you can do both `/directory` and `/directory/` transparently. If it is `'redirect'`, issue a HTTP 302 redirection to the url with trailing slash. - [`setHeaders`](#setheaders) Function to set custom headers on response. - `extensions` Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to `false`) diff --git a/index.js b/index.js index 18b4a36..a203c22 100644 --- a/index.js +++ b/index.js @@ -47,7 +47,7 @@ async function send (ctx, path, opts = {}) { const maxage = opts.maxage || opts.maxAge || 0 const immutable = opts.immutable || false const hidden = opts.hidden || false - const format = opts.format !== false + const format = (opts.format === false) ? false : (opts.format === 'redirect' ? 'redirect' : 'follow') const extensions = Array.isArray(opts.extensions) ? opts.extensions : false const brotli = opts.brotli !== false const gzip = opts.gzip !== false @@ -107,10 +107,15 @@ async function send (ctx, path, opts = {}) { // Format the path to serve static file servers // and not require a trailing slash for directories, // so that you can do both `/directory` and `/directory/` + // for 'follow', transparently send the file + // for 'redirect', give HTTP 302 redirection if (stats.isDirectory()) { - if (format && index) { + if (format === 'follow' && index) { path += `/${index}` stats = await fs.stat(path) + } else if (format === 'redirect' && index) { + ctx.redirect(ctx.request.path + '/' + ctx.request.search) + return true } else { return }