From 99d985e50b9894c4a2f79f442ed8250025c6065a Mon Sep 17 00:00:00 2001 From: Jannis Fedoruk-Betschki Date: Thu, 27 Jun 2024 17:20:07 +0200 Subject: [PATCH 1/2] 1.2.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8111a6c..44eae2b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ghost-bunnycdn-middleware", - "version": "1.1.3", + "version": "1.2.0", "description": "A middleware between a Ghost CMS instance and BunnyCDN, supposed to run in a Docker stack, alongside a Ghost container.", "main": "dist/index.js", "author": "Jannis Fedoruk-Betschki ", From f19b8d15ad469933c515f40eea47aac4bf3ad476 Mon Sep 17 00:00:00 2001 From: Jannis Fedoruk-Betschki Date: Sun, 30 Jun 2024 09:58:15 +0200 Subject: [PATCH 2/2] Refactor trailing slash middleware to handle excluded paths and improve redirection logic --- src/index.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index b94d178..96a2c9c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,7 +13,6 @@ const app = express(); app.use(bodyParser.json()); const PORT = process.env.PORT || 3000; -// remove trailing slash from GHOST_URL for consistency const GHOST_URL = process.env.GHOST_URL?.replace(/\/$/, ''); const BUNNYCDN_API_KEY = process.env.BUNNYCDN_API_KEY; const BUNNYCDN_PULL_ZONE_ID = process.env.BUNNYCDN_PULL_ZONE_ID; @@ -155,18 +154,21 @@ const purgeCache = async (): Promise => { app.use((req, res, next) => { const reqPath = req.path; - // Check if the path does not end with a slash, does not have a file extension, and does not include API endpoints + // Paths that should not have a trailing slash appended + const excludedPaths = ['/r/', '/api/']; + + // Check if the path ends with a slash or has a file extension or is an excluded path if ( - reqPath !== '/' && - !reqPath.endsWith('/') && - !path.extname(reqPath) && - !reqPath.includes('/api/') + reqPath.endsWith('/') || + path.extname(reqPath) || + excludedPaths.some((excludedPath) => reqPath.startsWith(excludedPath)) ) { - const query = req.url.slice(reqPath.length); - res.redirect(301, `${reqPath}/${query}`); - return; + return next(); } - next(); + + // If the path is not in the excluded list and does not end with a slash, append one + const query = req.url.slice(reqPath.length); + res.redirect(301, `${reqPath}/${query}`); }); app.use(async (req, res) => {