Gatsby netlify redirection issue

Viewed 152

I am using gatsby generated static site for my website and using Netlify to host it. I wanted to prevent redirection from non-trailing to trailing slash. One solution we implemented was to use a gatsby plugin to force non-trailing slash and disabled pretty URLs. but this causes both with and without slashed pages to return 200. I want to have my static site redirect 301 from trailing to non-trailing slash page.

1 Answers

Short answer: you can't redirect directly from a trailing slash to a non-trailing slash with this approach. From Netlify's docs:

You cannot use a redirect rule to add or remove a trailing slash.

What may work for you is using .htaccess approach but I'm not sure how it will behave in Netlify's environment. Something like this should work:

#### Force HTTPS://WWW and remove trailing / from files ####
## Turn on rewrite engine
RewriteEngine on

# Remove trailing slash from non-filepath urls
RewriteCond %{REQUEST_URI} /(.+)/$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ https://www.example.com/%1 [R=301,L]

# Include trailing slash on directory 
RewriteCond %{REQUEST_URI} !(.+)/$
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+)$ https://www.example.com/$1/ [R=301,L]

# Force HTTPS and WWW 
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC]
RewriteCond %{https} off  
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

To create a .htaccess in Gatsby, you can simply create it in the static folder and during the build process it will be transpiled/cloned into the /public folder or you can use the gatsby-plugin-htaccess plugin.

Related