Skip to content

Commit

Permalink
Prevent append of trailing slash in cases where path ends with a file…
Browse files Browse the repository at this point in the history
… extension

Canonical URLs specified in the metadata object are being resolved
incorrectly when the trailing slash config is set to true.  In cases
where the path ends with something like `.html` it will append the slash
resulting in `.html/` which causes issues for SEO.  This will validate
that if the path has an extension, no slash will be appended.
  • Loading branch information
kshehadeh committed Jun 7, 2024
1 parent 48396e8 commit 9826ad4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 7 additions & 0 deletions packages/next/src/lib/metadata/resolvers/resolve-url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ describe('resolveAbsoluteUrlWithPathname', () => {
'https://example.com/foo?bar'
)
})

it('should not add trailing slash to relative url that ends with a file extension', () => {
expect(resolver('/foo.html')).toBe('https://example.com/foo.html')
expect(resolver(new URL('/foo.html', metadataBase))).toBe(
'https://example.com/foo.html'
)
})
})
})

Expand Down
5 changes: 4 additions & 1 deletion packages/next/src/lib/metadata/resolvers/resolve-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ function resolveAbsoluteUrlWithPathname(
let isRelative = resolvedUrl.startsWith('/')
let isExternal = false
let hasQuery = resolvedUrl.includes('?')
let hasFileExtension = /\.[0-9a-z]+$/i.test(resolvedUrl)

if (!isRelative) {
try {
const parsedUrl = new URL(resolvedUrl)
Expand All @@ -121,7 +123,8 @@ function resolveAbsoluteUrlWithPathname(
// If it's not a valid URL, treat it as external
isExternal = true
}
if (!isExternal && !hasQuery) return `${resolvedUrl}/`
if (!hasFileExtension && !isExternal && !hasQuery)
return `${resolvedUrl}/`
}
}

Expand Down

0 comments on commit 9826ad4

Please sign in to comment.