1

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.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
NaughtySquid
  • 1,947
  • 3
  • 29
  • 44

1 Answers1

2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Interesting. It's VERY close, but oddly if the first "folder" has a hyphen in the name, it ends up going to the last rule and passing the path to index.php instead? – NaughtySquid Nov 12 '21 at 07:47
  • There is no hyphen check in `RewriteCond %{REQUEST_URI} ^(.+)/+$` besides by using `RewriteCond %{REQUEST_FILENAME} !-d` we are skipping all real folders. Real folders should always have a trailing `/` due to security reasons. – anubhava Nov 12 '21 at 07:51
  • Well, with this rule "RewriteRule ^support-us/?$ /index.php?module=support_us [N]" and your suggestion it ends up as "/support-us?module=support_us" instead of "/support-us". – NaughtySquid Nov 12 '21 at 08:02
  • That rule is not part of my answer. Is `/support-us/` a real directory? – anubhava Nov 12 '21 at 08:27
  • No, it's a rewrite rule to have a friendly URL for the page, as shown by my comment. – NaughtySquid Nov 12 '21 at 08:38
  • 1
    You need to edit your question to include ALL your rewrite rules. – Stephen Ostermiller Nov 12 '21 at 09:05
  • Check my update. You need to place `Options -MultiViews` at the top and always test after clearing browser cache. – anubhava Nov 12 '21 at 10:59