/

How I Solved the Trailing Slash Issue in Netlify Rewrites

How I Solved the Trailing Slash Issue in Netlify Rewrites

Netlify’s rewrite feature is incredibly useful for creating duplicate pages on my websites. By adding rules to the _redirects file in the project’s public root, I can easily create different URLs for my content. However, I encountered a problem with trailing slashes that needed to be addressed.

To illustrate, let’s say I have several pages under the directory content/original. I could use the following rewrite rule:

1
/copy/* /original/:splat 200

With this rule, accessing the URL /copy would show the content stored in https://mysite.com/original without changing the URL. This is because it’s not a redirect (despite the _redirects file name), but a rewrite, as indicated by the 200 code at the end. If I had used 301, it would have been a redirect.

The issue arose when I realized that there was no built-in way to automatically add a trailing slash to the URL. This led to problems when accessing /copy and /copy/ because relative URLs for images and links would break, resulting in 404 errors.

I searched for a solution within my static site generator, hoping to find an alternative method for handling redirects. However, I ultimately opted for a client-side solution, which turned out to be simple yet effective.

To resolve the trailing slash problem, I added a JavaScript snippet at the bottom of my pages:

1
2
3
4
5
6
7
<script>
(function() {
if (!location.href.endsWith('/')) {
window.location = location.href + '/';
}
}())
</script>

Now, if a page is accessed without a trailing slash, the snippet automatically reloads the page with the slash appended at the end. The process is so fast that it’s almost imperceptible to the user.

Tags: Netlify, Rewrites, Trailing Slash, Static Site Generator