How to remove trailing slash of url?

For example:
https://example.com/a/b/c/ ----> https://example.com/a/b/c

Here is what I have tried:


function hasTrailingSlash(event: FetchEvent): boolean {
  return /\/$/.test(event.request.url)
}

addEventListener('fetch', (event) => {
  event.respondWith(handleFetchEvent(event))
})

async function handleFetchEvent(event: FetchEvent) {
  if (hasTrailingSlash(event)) {
    const destinationURL = event.request.url.replace(/\/+$/, '')

    console.log('original URL', event.request.url)
    console.log('destination URL', destinationURL)

    const statusCode = 308
    return Response.redirect(destinationURL, statusCode)
  }

  ......
}

but with this I got ERR_TOO_MANY_REDIRECTS error… what’s wrong with my code?

If you’re trying this by going to the root domain of the website, it won’t work since the root domain always has a trailing slash (the HTTP path can never be empty, even if browsers don’t show that slash /). You could explicitly check to see if url.pathname is / and not perform the redirection in that case.

1 Like

@Judge Thanks! That works!!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.