-
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
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 has been a lot of cases lately when people copy and paste .htaccess to their existing development environment and gets redirect errors and 404 errors.
Here is a short instruction to show you how to integrate the rewrite rules with different CMS tools. There are 4 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
This usually happens to those have WordPress and did 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 RewriteBase and all along it has been working, keep that RewriteBase and don't remove it.