Home > database >  Remove trailing slash with htaccess with existing rules
Remove trailing slash with htaccess with existing rules

Time:11-16

I wish to remove a trailing slash when one is given using htaccess. What would be the best way to do it that will work with my existing rules as below:

  # make sure www. is always there
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
  
  # if requested url does not exist pass it as path info to index.php
  RewriteRule ^$ index.php?/ [QSA,L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule (.*) index.php?/$1 [QSA,L]

A sample URL would be something like:

https://www.example.com/this-test/

I of course want the ending slash removed.

I've tried this:

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

But that does not work with the existing rules that are there. It ends up redirecting to the index.php pages due to the other rules.

CodePudding user response:

Have it this way:

Options -MultiViews
DirectoryIndex index.php
RewriteEngine On

# add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(. )$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(. )/ $
RewriteRule ^ %1 [R=301,NE,L]

# if requested url does not exist pass it as path info to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [QSA,L]

Make sure to test it after completely clearing browser cache.

  • Related