Igor Moiseev Applied mathematician, Web Developer

Allow optional trailing slash in Apache with Rewrite moduleedit

Apache's handy mod_rewrite module is helping to correct this unfortunate human typos.

At first let's check whether the Apache's mod_rewrite is enabled.

# a2enmod rewrite
Module rewrite already enabled

If it was not, then reload configuration

# service apache2 reload
 * Reloading web server config apache2                      [OK]

to assure that the rewrite will work you need to assure the one more thing, it is AllowOverride option in the VirtualHost configuration

<VirtualHost *:80>


<Directory /var/www/example.com/htdocs>
        Options FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all



Now put the following snippet into .htaccess located in the folder of your website (/var/www/example.com/htdocs)

RewriteEngine On

# remove trailing slash
RewriteCond %{HTTPS} off
RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteRule ^(.+[^/])/$ https://%{HTTP_HOST}/$1 [R=301,L]

That's it, happy re-writing!