From 68f2d605c2a43a745004923557c65cd03098638c Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 25 May 2023 15:39:22 -0400 Subject: [PATCH] Redirect requests with pathname that ends with /index.md (#37302) --- middleware/handle-invalid-paths.js | 5 +++++ tests/rendering-fixtures/bad-urls.js | 14 ++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 tests/rendering-fixtures/bad-urls.js diff --git a/middleware/handle-invalid-paths.js b/middleware/handle-invalid-paths.js index 2a8acda843..47243f628e 100644 --- a/middleware/handle-invalid-paths.js +++ b/middleware/handle-invalid-paths.js @@ -31,5 +31,10 @@ export default function handleInvalidPaths(req, res, next) { return res.status(404).send('Not found') } + if (req.path.endsWith('/index.md')) { + defaultCacheControl(res) + return res.redirect(req.path.replace(/\/index\.md$/, '')) + } + return next() } diff --git a/tests/rendering-fixtures/bad-urls.js b/tests/rendering-fixtures/bad-urls.js new file mode 100644 index 0000000000..e8ab92f194 --- /dev/null +++ b/tests/rendering-fixtures/bad-urls.js @@ -0,0 +1,14 @@ +import { head } from '../helpers/e2etest.js' + +describe('bad URLs', () => { + test('any URL with /index.md suffix redirects to be without suffix', async () => { + const URLs = ['/index.md', '/en/index.md', '/en/actions/index.md'] + for (const url of URLs) { + const res = await head(url) + expect(res.statusCode).toBe(302) + expect(res.headers.location).toBe(url.replace(/\/index\.md$/, '')) + expect(res.headers['cache-control']).toContain('public') + expect(res.headers['cache-control']).toMatch(/max-age=[1-9]/) + } + }) +})