How to Add Trailing Slash in Apache

add trailing slash in apache

Sometimes, you might need to add trailing slash to all URLs on your website, except files such as CSS, JS. This can be a little tricky and if not implemented properly, can lead to redirect loops on your website. So let us take a look at how to add trailing slash in Apache.


How to Add Trailing Slash in Apache

Here are the steps to add trailing slash in Apache.

Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:


Place your .htaccess file in the root document folder of your website (/var/www/html).


1. Open .htaccess file

Open .htaccess file in a text editor

$ sudo vim /var/www/html/.htaccess


2. Add trailing slash

Add the following lines to your .htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On

#force trailing slashes on real directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L]



The above code will add trailing slash on all URLs except file names such as css, js, image files.



3. Restart Apache web server

Restart Apache web server to apply changes

$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]




About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!