-
Notifications
You must be signed in to change notification settings - Fork 0
trailing slash redirects
Trailing slash redirects can be done by adding one of the options below in .htaccess
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]
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:
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.
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]
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
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.