Cookie Consent by Free Privacy Policy Generator Allow optional trailing slash in Apache with Rewrite module | Igor Moiseev

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
</Directory>

....

</VirtualHost>

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 ^(.+[^/])/$ https://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteRule ^(.+[^/])/$ https://%{HTTP_HOST}/$1 [R=301,L]

That’s it, happy re-writing!

moiseevigor.github.io is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means to earn fees when linking to Amazon.com and affiliated sites.