Skip to content

Commit

Permalink
[DEV-1406] Handle the trailing slash of the URL (#685)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremygordillo authored Feb 27, 2024
1 parent f564577 commit 2f76678
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/moody-cats-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"cloudfront-functions": patch
---

[DEV-1406] Fix the trailing slash of the URL
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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('/');
});
});
18 changes: 10 additions & 8 deletions apps/cloudfront-functions/src/viewer-request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 2f76678

Please sign in to comment.