Redirect all urls to trailing slash while avoiding a 301 redirect to a 404 page

Hey hey

One of the requirements of a site we're working on is to end all URL's with a trailing slash.

All URL's are currently redirected to their trailing slash version in middleware.
if (!context.route.path.endsWith('/')) {
context.redirect(301, context.route.path + '/')
}

When you visit /foo/bar you're 301 redirected to /foo/bar/ which is a 404 page.
The problem is this will show as:
curl -I site.com/foo/bar
HTTP/2 301
location: /foo/bar/

We want all non trailing slashes to be redirected to their trailing slash versions as a 301.
so /contact-us = /contact-us/

I understand why this happens, it's before any requests to Prismic have been made, we don't know the page is a 404 yet.

Have you seen this before and have any ideas how to enforce trailing slash after fetching successful without updating every page view with the redirect inside the asyncdata?

Thanks
Jake

Solved this by creating a global plugin that is only run after Prismic page api calls have been made/successful.

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

Hi Jake,

I've got the trailing slash enabled in both the route and sitemap configs, but still getting redirected to the 404 when accessing the url without the trailing slash. Also in static mode.

Any chance you can share your solution?

Chris

Hey Chris,

We create a 301 redirect to the trailing slash version.
We don't have the trailing slash mode enabled in the config.

Global plugin here:

export default ({ route, redirect }, inject) => {
    // All urls to end with trailing slash
    inject('trailingSlash', () => {
        if (!route.path.endsWith('/')) {
          redirect(301, route.path + '/')
      }
    })
}

Then in middleware/asyncData I pass ({ $trailingSlash()'.. }) and call $trailingSlash().

There is probably a much better way of dealing with this but this solved our issues.

You could also just use the conditional without creating the plugin.

if (!route.path.endsWith('/')) {
    redirect(301, route.path + '/')
}

Hope this helps

3 Likes

Hey Jake!

Thank you so much for posting your solution :slight_smile: I manually added redirects for all the sites urls, which works, but obviously isn't practical for the long term. I'll give your approach a go and see if that helps.

Thanks again :smiley:

Cheers,
Chris

2 Likes