Dealing with Trailing Slashes in Statamic

As I recently relaunched this site I have been following Google's Webmaster Tools closely and noticed crawl errors where any entry with a trailing slash was returning a 404. This simple edit to your original Statamic .htaccess file will automatically redirect URLs with trailing slashes.

Webmaster Tools Crawl Errors

To be more specific about the issue. Google was trying to index 2 URLs

  • http://johnhenry.ie/articles/eeuk-2013 - 200 Success
  • http://johnhenry.ie/articles/eeuk-2013/ - 404 Not Found

Now Statamic automatically removes the trailing slash from URLs but doesn’t account for the fact that users or site creators may in fact add a slash in their templates or some third party might link to their pages inadvertently adding the slash.

The following amendment to the default htaccess fixes this

RewriteRule ^(_app) - [F,L]
RewriteRule ^(_config) - [F,L]
RewriteRule ^(_content) - [F,L]
RewriteRule ^(.*).yml$ - [F,L]
RewriteRule ^(.*).yaml$ - [F,L]
RewriteRule ^(.*).html$ - [F,L]
RewriteRule ^(.*/)?\.git+ - [F,L]

# Remove trailing slash and redirect URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} (.*)$
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [QSA,L]

Statamic Installation Docs