10

I have a rule in my htaccess file to remove any extra trailing slashes from a url, this works on sub-directories with any more than 1 trailing slash. However it doesn't work on the root; which i need it to do.

For example.

http://www.example.com/test//// Redirects to http://www.example.com/test/

http://www.example.com/// Needs to redirect to http://www.example.com

Any ideas on what i need to add?. Cheers.

RewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$
RewriteRule . %1/ [R=301,L]
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
LazyAlpine
  • 101
  • 1
  • 8

4 Answers4

9

For removing multiple slashes anywhere in REQUEST_URI this rule works best:

RewriteEngine On
    
RewriteCond %{THE_REQUEST} \s[^?]*//
RewriteRule ^.*$ /$0 [R=301,L,NE]

It takes advantage of the fact that mod_rewrite engine itself converts all multiple forward slashes to a single slash in the RewriteRule pattern. We use RewriteCond %{THE_REQUEST} to make sure original REQUEST_URI contains multiple slashes.

Here [^?]*// matches 2 // before matching query string since [^?] matches anything except ?. This will allow // in query string.

anubhava
  • 761,203
  • 64
  • 569
  • 643
4

Try with:

RewriteCond %{REQUEST_URI} ^(.*?)//+$
RewriteRule ^ %1/ [R=301,L]
Croises
  • 18,570
  • 4
  • 30
  • 47
1

You htaccess works great as you can test on below link

https://htaccess.madewithlove.be/

Working

So you need to make sure you test either with a Chrome Incognito window or using like below

curl -v http://example.com////

I usually prefer curl as I know it will give a fresh response from the server always

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
0

You just need two rule to match two different pattern

RewriteCond %{REQUEST_URI} ^(?:/){2,}$
RewriteRule . / [R=301,L]

RewriteCond %{REQUEST_URI} ^(.*?)(?:/){2,}$
RewriteRule . %1/ [R=301,L]
Dennis C
  • 24,511
  • 12
  • 71
  • 99