Skip to content

trailing slash redirects

randomecho edited this page Apr 1, 2012 · 2 revisions

Trailing slash redirects

Trailing slash redirects can be done by adding one of the options below in .htaccess

Option 1

Rewrite "domain.com/foo -> domain.com/foo/"

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]

Option 2

Rewrite "domain.com/foo/ -> domain.com/foo"

RewriteRule ^(.*)/$ $1 [R=301,L]

There have been a lot of cases where people copy and paste the .htaccess file to their existing development environment and get redirect and 404 errors.

Here are some tips to show you how to integrate the rewrite rules with different CMS tools. There are four areas you need to look out for:

1. Keep a backup

If you use trailing slash redirects on an existing site, always keep a backup of your .htaccess and test thoroughly on your staging server before using it on a production server.

2. Don't replace existing rules, merge

For example, if you use CodeIgniter you may have existing URL rewrite rules like:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

Merge the above with H5BP rules below:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]

3. Be careful of the order

Make sure you test thoroughly in your staging environment. For the above example, the order is add trailing slash first, and add your existing rule after:

# this adds trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]

# this gets rid of index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

4. Double-check RewriteBase path is correct

Make sure your RewriteBase path points to the correct location and sits above any rewrite rules. This usually happens to those have WordPress and ran the auto install. For instance, if you have a site at example.com/blog, your RewriteBase may look like:

RewriteBase /blog/

If you already have a working RewriteBase, keep that and don't remove it.

Clone this wiki locally