How to Remove Trailing Slash from URL in Apache


remove trailing slash url apache

Trailing slash in URLs can make them look ugly. Here’s how to remove trailing slash from URL in Apache. There are 2 ways to do it – using .htaccess and virtual host file.

 

How to Remove Trailing Slash from URL in Apache

Here are the steps to remove trailing slash from URL in Apache. We have 2 options – modify the .htacces file or virtual hosts files. We will look at each method separately.

 

Using .htaccess file

Open your .htaccess file (usually at /var/html/www) and paste the 2 lines highlighted in bold below


<IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
  Options -MultiViews
 </IfModule>

 RewriteEngine on
 RewriteBase /

 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)/$ /$1 [L,R=301]

 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule . /index.php [L]
</IfModule>

 

Make sure these lines are in the same order as shown above – below “RewriteBase /” and above “RewriteRule ^index\.php$ – [L]

 

Using virtual host file

Open your virtual host file in a text editor and paste the 2 lines highlighted in bold below.


<VirtualHost 127.0.0.1:80>
 ServerName my.server
 DocumentRoot /var/www/html
 ServerAdmin webmaster@localhost

 <IfModule mod_rewrite.c>
  <IfModule mod_negotiation.c>
   Options -MultiViews
  </IfModule>

  RewriteEngine on
  RewriteBase /

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)/$ /$1 [L,R=301]

  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule . /index.php [L]
 </IfModule>
</VirtualHost>

 

Again, make sure you add these lines at the same location as shown above.

 

Restart Apache Server

Restart Apache web server to apply changes

CentOS/Fedora/RHEL


/etc/init.d/httpd restart 

 

Ubuntu/Debian/LinuxMint


sudo /etc/init.d/apache2 restart 

 

 

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!