diff --git a/.changeset/moody-cats-bow.md b/.changeset/moody-cats-bow.md new file mode 100644 index 0000000000..6e054b8477 --- /dev/null +++ b/.changeset/moody-cats-bow.md @@ -0,0 +1,5 @@ +--- +"cloudfront-functions": patch +--- + +[DEV-1406] Fix the trailing slash of the URL diff --git a/apps/cloudfront-functions/src/__tests__/viewer-request-handler.test.ts b/apps/cloudfront-functions/src/__tests__/viewer-request-handler.test.ts index 24ad9ae45a..0ae07a44d5 100644 --- a/apps/cloudfront-functions/src/__tests__/viewer-request-handler.test.ts +++ b/apps/cloudfront-functions/src/__tests__/viewer-request-handler.test.ts @@ -30,7 +30,7 @@ const makeEvent = (uri: string): AWSCloudFrontFunction.Event => ({ describe('handler', () => { it('should append the html suffix', () => { expect(handler(makeEvent('/page')).uri).toBe('/page.html'); - expect(handler(makeEvent('/page/')).uri).toBe('/page/'); + expect(handler(makeEvent('/page/')).uri).toBe('/page.html'); expect(handler(makeEvent('/image.jpg')).uri).toBe('/image.jpg'); expect(handler(makeEvent('/font.woff2')).uri).toBe('/font.woff2'); const example0 = '/i-s/g/mo/v1.0/i-p/p-i/v-d'; @@ -43,4 +43,8 @@ describe('handler', () => { '/gitbook/docs/n/.gitbook/assets/0' ); }); + + it('should not add the html suffix to homepage', () => { + expect(handler(makeEvent('/')).uri).toBe('/'); + }); }); diff --git a/apps/cloudfront-functions/src/viewer-request-handler.ts b/apps/cloudfront-functions/src/viewer-request-handler.ts index 04dcdea4d8..ecd9ce1643 100644 --- a/apps/cloudfront-functions/src/viewer-request-handler.ts +++ b/apps/cloudfront-functions/src/viewer-request-handler.ts @@ -16,15 +16,17 @@ const handler = ( // Check if the uri refers to a gitbook assets const isGitbookAssets = uri.startsWith('/gitbook/docs'); const isWoff2 = uri.endsWith('.woff2'); // woff2 is a font format + const uriEndsWithSlash = uri.endsWith('/'); + const isHomepage = uri === '/'; - // Add the .html extension if missing - if ( - !uri.endsWith('/') && - !isGitbookAssets && - !isWoff2 && - !/\.[a-zA-Z]+$/.test(uri) - ) { - request.uri += '.html'; + if (!isHomepage) { + if (uriEndsWithSlash) { + request.uri = uri.replace(/\/$/, ''); + } + // Add the .html extension if missing + if (!isGitbookAssets && !isWoff2 && !/\.[a-zA-Z]+$/.test(uri)) { + request.uri += '.html'; + } } return request;